在Entityframework中绘制1:*关系的映射类 - ASP.NET MVC [英] mapping classes for 1:* relationship in Entityframework - ASP.NET MVC
问题描述
我正在使用asp.net mvc应用程序,并使用数据注释来在实体框架类中映射数据库表。现在我有两个表,例子表X和表Y与多对多关系,所以在'table-XY'之间引入另一个表来排序到一个很多的关系....我如何去映射表-XY?我把iCollectiontable-XY放在table-X中,对于表Y来说是一样的吗?我需要一些绘图指导!
i am working on asp.net mvc app and using data annotation to map database table in entity framework classes. Now i have two table say example table-X and table-Y with many-to-many relationship so introduce another table in between 'table-XY' to sort to one-many relationship.... how i am going to map table-XY? do i put iCollectiontable-XY in table-X and same for table-Y?? i need some guidance for mapping!
[Table("table-X")]
public class table-X
{
public table-X()
{
}
[Key]
public int table-XID { get; set; }
public string Title { get; set; }
....
???
}
table-Y
table-Y
[Table("table-Y")]
public class table-Y
{
public table-Y()
{
}
[Key]
public int table-YID { get; set; }
public string Title { get; set; }
....
???
}
table-XY
table-XY
[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; }
....
????
}
推荐答案
你不需要表XY在您的实体框架模型中。简单地定义每个类型的集合导航属性:
You don't need table XY in your entity framework model. Simply define collection nav properties for each type:
[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:
If you want more control over the name of the many-to-many relationship table, use fluent 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();
}
这篇关于在Entityframework中绘制1:*关系的映射类 - ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!