mapping classes for 1:* relationship in Entityframework - ASP.NET MVC

浪子不回头ぞ 提交于 2019-12-11 18:14:47

问题


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-X

[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("table-Y")]
public class table-Y
{
    public table-Y()
    {

    }

    [Key]
    public int table-YID { get; set; }
    public string Title { get; set; }
    ....
    ???
}

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; }
    ....
    ????
}

回答1:


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; }
}

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" );
        } );

Usage:

using( var db = new YourDbContext() ) 
{
    var tagToAddToPost = db.Tags.Find( <tagId> );
    var targetPost = db.Posts.Find( <postId> );

    targetPost.Tags.Add( tagToAddToPost );

    db.SaveChanges(); 
}


来源:https://stackoverflow.com/questions/21329462/mapping-classes-for-1-relationship-in-entityframework-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!