Programing

다 대다 매핑 테이블

lottogame 2020. 12. 5. 09:08
반응형

다 대다 매핑 테이블


온라인과 Programming Entity Framework CodeFirst 책에서 본 예제에서 두 클래스 모두에 컬렉션이있을 때 EF는 다음과 같은 매핑 테이블을 만들고 MembersRecipes각 클래스의 기본 키는이 테이블에 연결됩니다.

그러나 아래 작업을 수행하면 대신 Recipes테이블에 새 필드와 테이블에 Member_Ida가 표시 Recipe_Id됩니다 Members.

두 개의 일대 다 관계 만 생성하지만 다 대다 관계는 아니므로 멤버 3을 레시피 (4,5,6)에 연결하고 레시피 4를 멤버 (1,2,3) 등에 연결할 수 있습니다.

이 매핑 테이블을 만드는 방법이 있습니까? 그렇다면 "요리 책"과 같은 다른 이름을 어떻게 지정합니까?

감사

    public abstract class Entity {
        [Required]
        public int Id { get; set; }
    }   

    public class Member : Entity {
        [Required]
        public string Name { get; set; }

        public virtual IList<Recipe> Recipes { get; set; }
    }

    public class Recipe : Entity {  
        [Required]
        public string Name { get; set; }

        [ForeignKey("Author")]
        public int AuthorId { get; set; }
        public virtual Member Author { get; set; }

            ....

        public virtual IList<Member> Members { get; set; }
    }

업데이트 : 아래 유창함 API를 사용하여 대체하지 않습니다 내가 시도 또 다른 접근 방식 AuthorId및을 AuthorRecipe소유자 플래그는, 나 또한로부터 예를 들어 아래의 이름을 바꾼 CookbooksMembersRecipes언급 한 바와 같이이있다 이것은 또한 대답과 유사한 내 문제를 해결하지만, 추가 의미.

public class MembersRecipes {

    [Key, Column(Order = 0)]
    [ForeignKey("Recipe")]
    public int RecipeId { get; set; }
    public virtual Recipe Recipe { get; set; }

    [Key, Column(Order = 1)]
    [ForeignKey("Member")]
    public int MemberId { get; set; }
    public virtual Member Member { get; set; }

    public bool Owner { get; set; }
}

그리고 Recipe& Member수업에서 나는 컬렉션을

public virtual IList<MembersRecipes> MembersRecipes { get; set; }

DbContext OnModelCreating에서 다음을 수행하십시오.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{    
    modelBuilder.Entity<Recipe>()
        .HasMany(x => x.Members)
        .WithMany(x => x.Recipes)
    .Map(x =>
    {
        x.ToTable("Cookbooks"); // third table is named Cookbooks
        x.MapLeftKey("RecipeId");
        x.MapRightKey("MemberId");
    });
}

다른 방법으로도 할 수 있습니다. 똑같은 동전의 다른 면일뿐입니다.

modelBuilder.Entity<Member>()
    .HasMany(x => x.Recipes)
    .WithMany(x => x.Members)
.Map(x =>
{
  x.ToTable("Cookbooks"); // third table is named Cookbooks
  x.MapLeftKey("MemberId");
  x.MapRightKey("RecipeId");
});

추가 예 :

http://www.ienablemuch.com/2011/07/using-checkbox-list-on-aspnet-mvc-with_16.html

http://www.ienablemuch.com/2011/07/nhibernate-equivalent-of-entity.html


최신 정보

Author 속성에 대한 순환 참조를 방지하려면 위와 별도로 다음을 추가해야합니다.

modelBuilder.Entity<Recipe>()
    .HasRequired(x => x.Author)
    .WithMany()
    .WillCascadeOnDelete(false);

Idea sourced here: EF Code First with many to many self referencing relationship

The core thing is, you need to inform EF that the Author property(which is a Member instance) has no Recipe collections(denoted by WithMany()); that way, cyclical reference could be stopped on Author property.

These are the created tables from the Code First mappings above:

CREATE TABLE Members(
    Id int IDENTITY(1,1) NOT NULL primary key,
    Name nvarchar(128) NOT NULL
);


CREATE TABLE Recipes(
    Id int IDENTITY(1,1) NOT NULL primary key,
    Name nvarchar(128) NOT NULL,
    AuthorId int NOT NULL references Members(Id)
);


CREATE TABLE Cookbooks(
    RecipeId int NOT NULL,
    MemberId int NOT NULL,
    constraint pk_Cookbooks primary key(RecipeId,MemberId)
);

참고URL : https://stackoverflow.com/questions/11382783/many-to-many-mapping-table

반응형