How to set a 0..* relationship in Entity Framework Code First?

别说谁变了你拦得住时间么 提交于 2020-01-01 04:38:09

问题


I have the next code for two classes:

public class Object
{
    public int ObjectID { get; set; }

    public int Object2ID { get; set; }
    public virtual Object2 Object2 { get; set; }
}

public class Object2
{
    public int Object2ID { get; set; }

    public virtual ICollection<Object> Objects { get; set; }
}

I know that with Entity Framework, this will create a one-to-many relationship, but what I want to know, is how to transform this to a zero-to-many relationship.

I'm new to Entity Framework and I couldn't find any direct answer around.


回答1:


For a 0-to-many relationship in Entity Framework, have the foreign key be nullable.

public int? Object2ID { get; set; }



回答2:


Another way to do this is by using Fluent API:

public class YouDbContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder mb)
    {
        mb.Entity<Object2>
            .HasMany(o1 => o1.Objects)
            .WithOptional(o2 => o2.Object2);

        base.OnModelCreating(mb);
    }
}


来源:https://stackoverflow.com/questions/25895479/how-to-set-a-0-relationship-in-entity-framework-code-first

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