重用多对多表

时间:2016-03-03 18:10:14

标签: .net entity-framework

我有以下模型

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class DealGroup {
    public int Id { get; set; }
    public string GroupName { get; set; }
    public ICollection<Person> PeopleInGroup { get; set; }
    public Deal Deal { get; set; }
}

public class Deal
{
    public int Id { get; set; }
    public DateTime TimeOfDeal { get; set; }
    public DealGroup FromGroup { get; set; }
    public DealGroup ToGroup { get; set; }
}

这个想法是在两组人之间进行“交易”(Deal-&gt; FromGroup,Deal-&gt; ToGroup)。在OnModelCreating(我先使用代码)中我说:

        modelBuilder.Entity<Deal>()
            .HasRequired(t => t.FromGroup)
            .WithRequiredPrincipal(t => t.Deal);

        modelBuilder.Entity<Deal>()
            .HasRequired(t => t.ToGroup)
            .WithRequiredPrincipal(t => t.Deal);

创建数据库时出错。我相信错误是因为我正在两次映射DealGroup的Deal属性。当我添加2个属性时:

public Deal DealTo { get; set; }
public Deal DealFrom { get; set; }

并将每个映射到他们自己的导航属性都很好,但这会带来非常不受欢迎的代码。我希望有一个属性可以回到最初的Deal对象,无论你是ToGroup Group还是FromGroup Group。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以这样重新配置(根据需要重命名):

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Group {
    public int Id { get; set; }
    public string GroupName { get; set; }
    public ICollection<Person> PeopleInGroup { get; set; }
    public ICollection<Deal> DealsFrom { get; set; }
    public ICollection<Deal> DealsTo { get; set; }
}

public class Deal
{
    public int Id { get; set; }
    public DateTime TimeOfDeal { get; set; }
    public ICollection<Group> FromGroups { get; set; }
    public ICollection<Group> ToGroups { get; set; }
}

流利代码:

modelBuilder.Entity<Deal>()
            .HasMany(d => d.FromGroups)
            .WithMany(d => d.DealsFrom)
            .Map(d =>
            {
                d.ToTable("FromGroups");
                d.MapLeftKey("DealId");
                d.MapRightKey("GroupId");
            });

modelBuilder.Entity<Deal>()
            .HasMany(d => d.ToGroups)
            .WithMany(d => d.DealsTo)
            .Map(d =>
            {
                d.ToTable("ToGroups");
                d.MapLeftKey("DealId");
                d.MapRightKey("GroupId");
            });