简体   繁体   English

如何配置多对多实体框架关系,但要同一个对象? EF6

[英]How to configure many-to-many entity framework relationship, but to same object? EF6

I have a class, like so 我有课,像这样

public MyObject {
    public long Id { get; set; }
    public string Name {get; set; }
}

I would like to setup a link between this class and another object of the same type. 我想在此类和另一个相同类型的对象之间建立链接。 So i need another object to handle the many-to-many relationship, which is fine, something like this 所以我需要另一个对象来处理多对多关系,这很好,像这样

public MyRelationship {
    public long Id { get; set; }
    public string Name { get; set; }
}

But how do i configure the rest. 但是我如何配置其余的。 I have tried examples online, but they are too different objects. 我在网上尝试过示例,但它们实在太不同了。

I have tried adding to navigation properties to MyRelationship for the link, like so 我已经尝试将导航属性添加到MyRelationship中以供链接使用,如下所示

public MyRelationship {
    public long Id { get; set; }
    public string Name { get; set; }

    public MyObject Parent { get; set; }
    public MyObject Child { get; set; }
}

And also 2 collections to MyObject, like so 还有MyObject的2个集合,像这样

public MyObject {
    public long Id { get; set; }
    public string Name {get; set; }

    public virtual ICollection<MyRelationship> ParentRelationships { get; set; }

    public virtual ICollection<MyRelationship> ChildRelationships { get; set; }
}

Then in my configuration file i have added 然后在我的配置文件中添加了

// relationships
this.HasMany(e => e.ParentRelationships)
    .WithRequired(e => e.Parent)
    .HasForeignKey(e => e.ParentId)
    .WillCascadeOnDelete(false);

this.HasMany(e => e.ChildRelationships)
    .WithRequired(e => e.Child)
    .HasForeignKey(e => e.ChildId)
    .WillCascadeOnDelete(false);

But i get errors, like this 但是我得到这样的错误

he navigation property 'ChildRelationships' declared on type 'MyObject' has been configured with conflicting foreign keys. 在类型“ MyObject”上声明的导航属性“ ChildRelationships”已配置有冲突的外键。

Why don't you just do this? 你为什么不这样做呢?

public MyObject{
    public long Id { get; set; }
    public string Name { get; set; }

    public ICollection<MyObject> Parents { get; set; }
    public ICollection<MyObject> Children { get; set; }
}

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

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