我正在使用asp.net mvc app并使用数据注释来映射实体框架类中的数据库表。现在我有两个表说例子table-X和table-Y有多对多的关系所以在'table-XY'之间引入另一个表来排序到一对多的关系....我将如何去映射表-XY?我把iCollectiontable-XY放在表-X中,同样用于表-Y ??我需要一些映射指导!
[Table("table-X")]
public class table-X
{
public table-X()
{
}
[Key]
public int table-XID { get; set; }
public string Title { get; set; }
....
???
}
[Table("table-Y")]
public class table-Y
{
public table-Y()
{
}
[Key]
public int table-YID { get; set; }
public string Title { get; set; }
....
???
}
[Table("table-XY")]
public class table-X
{
public table-XY()
{
}
[Key]
public int table-XYID { get; set; }
public int table-XID { get; set; }
public int table-YID { get; set; }
....
????
}
答案 0 :(得分:2)
您的实体框架模型中不需要表XY。只需为每种类型定义集合导航属性:
[Table("Post")]
public class Post
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
[Table("Tag")]
public class table-Y
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
如果您想要更多地控制多对多关系表的名称,请使用流畅的API:
modelBuilder.Entity<Post>()
.HasMany( p => p.Tags )
.WithMany( t => t.Posts )
.Map( emc =>
{
// table name
emc.ToTable( "PostTagMap" );
// column names
emc.MapLeftKey( "Post_id" );
emc.MapRightKey( "Tag_id" );
} );
用法:
using( var db = new YourDbContext() )
{
var tagToAddToPost = db.Tags.Find( <tagId> );
var targetPost = db.Posts.Find( <postId> );
targetPost.Tags.Add( tagToAddToPost );
db.SaveChanges();
}