java实现多对多关系的方法_MVC实现多对多的关系

EF具有多对多关系的默认约定 . 无需创建具体的

映射类 . 您必须在"FirstTable"和"SecondTable" Class中包含导航属性,如下所示 .

public class FirstTable

{

public FirstTable()

{

secondTableProperties = new HashSet();

}

public int Id { get; set; }

public int MyProperty2 { get; set; }

public int MyProperty3 { get; set; }

public virtual ICollection secondTableProperties { get; set; }

}

public class SecondTable

{

public SecondTable()

{

FirstTableProperties = new HashSet();

}

public int Id { get; set; }

public int MyProperty2 { get; set; }

public int MyProperty3 { get; set; }

public virtual ICollection FirstTableProperties { get; set; }

}

从DBContext中删除映射类,仅包括上面两个类 . 构建并运行应用程序,EF将自动在SQL Server中创建Mapping表 . 通常,映射表仅包含其他两个表的主键 .

您可以使用Fluent API对创建的映射表进行一些控制

modelBuilder.Entity()

.HasMany(s => s.FirstTableProperties)

.WithMany(c => c.secondTableProperties)

.Map(cs =>

{

cs.MapLeftKey("FirstTableId");

cs.MapRightKey("SecondTableId");

cs.ToTable("ManyToManyTable");

});

如果您想使用具有其他属性的连接表,则上述多对多关系将无效 . 在这种情况下,您将必须创建两个一对多关系,如下所示 .

public class FirstTable

{

public int Id { get; set; }

public int MyProperty2 { get; set; }

public virtual ICollection manytomany { get; set; }

}

public class SecondTable

{

public int Id { get; set; }

public int MyProperty2 { get; set; }

public virtual ICollection manytomany { get; set; }

}

public ManyToManyTable

{

[Required]

[Key, Column(Order=0)]

public int firsttableid { get; set; }

[Required]

[Key, Column(Order=1)]

public int secondtableid { get; set; }

public int AdditionalProperty { get; set; }

public virtual FirstTable first { get; set; }

public virtual SecondTable Second { get; set; }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值