0

我有这个实体:

public class Content
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Test { get; set; }
    public DateTime Date { get; set; }
}

我想用代码优先的附加字段与自身创建多对多关系,如下图所示:

在此处输入图像描述

我怎样才能做到这一点?

4

1 回答 1

2

我认为您想要以下内容:

public class Content
{
    public int Id { get; set; }
    public ICollection<ContentLink> OtherContents { get; set; }
}

public class ContentLink
{
    public int Id { get; set; }
    public Content Lhs{ get; set; }
    public Content Rhs{ get; set; }
    //other stuff
}

modelBuilder.Entity<Content>().
    HasMany(c => c.OtherContents).WithRequired(c=>c.Lhs);
modelBuilder.Entity<ContentLink>().
    HasRequired(c => c.Rhs).WithMany();

注意:以上内容仅允许您遍历该实体链接到的资源,而不是链接到您的其他实体

在此处查看我关于导航属性的帖子以获取更多详细信息:http: //blog.staticvoid.co.nz/2012/7/17/entity_framework-navigation_property_basics_with_code_first

于 2013-04-14T05:47:21.013 回答