Specifying Foreign Key Entity Framework Code First, Fluent Api

微笑、不失礼 提交于 2021-02-07 12:50:26

问题


I have a question about defining Foreign Key in EF Code First Fluent API. I have a scenario like this:

Two class Person and Car. In my scenario Car can have assign Person 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);
    }
}

In my sample I want to rename foreign key PersonId to PPPPP. In my mapping I say:

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

But my relationship is one to zero and I'm afraid I do mistake using WithMany method, but EF generate database with proper mappings, and everything works well.

Please say if I'm wrong in my Fluent API code or it's good way to do like now is done.

Thanks for help.


回答1:


I do not see a problem with the use of fluent API here. If you do not want the collection navigational property(ie: Cars) on the Person class you can use the argument less WithMany method.



来源:https://stackoverflow.com/questions/9858897/specifying-foreign-key-entity-framework-code-first-fluent-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!