I have a question about defining a foreign key in the EF Code First Fluent API. I have a scenario like this:
Two class people and a car. In my script, Car can assign Person or not (one or zero relation). The code:
public class Person { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } public class Car { public int Id { get; set; } public string Name { get; set; } public Person Person { get; set; } public int? PPPPP { get; set; } } class TestContext : DbContext { public DbSet<Person> Persons { get; set; } public DbSet<Car> Cars { get; set; } public TestContext(string connectionString) : base(connectionString) { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Car>() .HasOptional(x => x.Person) .WithMany() .HasForeignKey(x => x.PPPPP) .WillCascadeOnDelete(true); base.OnModelCreating(modelBuilder); } }
In my example, I want to rename the PersonId foreign key to PPPPP. In my cartography, I say:
modelBuilder.Entity<Car>() .HasOptional(x => x.Person) .WithMany() .HasForeignKey(x => x.PPPPP) .WillCascadeOnDelete(true);
But my relationship is null, and I'm afraid I'm wrong using the WithMany method, but EF generates a database with matching mappings and everything works well.
Tell me if I am mistaken in my Fluent API code, or is this a good way to do, as of now.
Thanks for the help.
source share