First, define the Foreign Key Entity Framework Code, then use Fluent Api.

ef-code-first entity-framework fluent-interface foreign-keys

Question

Regarding the EF Code First Fluent API's definition of Foreign Key, I have a query. I have the following situation:

Person and car of two classes. In my situation, a person may be assigned to the car or not (one or zero relationship). 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);
    }
}

I want to rename the foreign key PersonId in my sample to PPPPP. In my map, I write:

modelBuilder.Entity<Car>()
            .HasOptional(x => x.Person)
            .WithMany()
            .HasForeignKey(x => x.PPPPP)
            .WillCascadeOnDelete(true);

But because my connection is one to zero, I'm concerned I used the WithMany method incorrectly. Nevertheless, EF creates a database with accurate mappings, and everything works as it should.

Please let me know whether my Fluent API code is incorrect or if the current method is the best one.

I appreciate your assistance.

1
7
11/24/2017 10:19:43 PM

Accepted Answer

I don't see anything wrong with using fluent API in this situation. If the collection navigational property is not what you desire (i.e.Cars ) on thePerson You may use the argument less in class.WithMany method.

3
3/25/2012 9:00:08 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow