简体   繁体   English

如何在Entity Framework Code First中设置0 .. *关系?

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

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. 我知道使用Entity Framework,这将创建一对多关系,但我想知道的是如何将其转换为零对多关系。

I'm new to Entity Framework and I couldn't find any direct answer around. 我是Entity Framework的新手,我找不到任何直接的答案。

对于Entity Framework中的0对多关系,使外键可以为空。

public int? Object2ID { get; set; }

Another way to do this is by using Fluent API: 另一种方法是使用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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM