2012-08-25 2 views
4

박람회 목록 및 출품자 목록을 갖고 싶습니다.MVC EF 코드 첫 번째 일대일 관계 오류

스탠드 목록은 전시 업체 목록과는 별도로 제공되지만 등록이 완료되면 출품 업체가 스탠드를 예약 할 수 있기를 바랍니다.

스탠드를 선택/예약 할 때 - 내보기에 스탠드 목록을 표시 할 수 있고 예약 한 관련 출품자를 표시 할 수 있기를 원합니다.

마찬가지로, 나는 다른 관점에서, 전시자들과 그들이 어떤 입장을 취하고 있는지를리스트하고 싶다.

그래서 (EF CodeFirst를 사용하여) 일대일 관계를 설정하려고합니다. 그러나

, 스탠드 또는 전시 중 하나의 컨트롤러를 추가하려고 할 때, 나는 다음과 같은 오류 얻을 :

내 모델

enter image description here은 다음과 같습니다

public class Stand 
{ 
    public int StandID { get; set; } 
    public string Description { get; set; } 
    public bool Booked { get; set; } 
    public int ExhibitorID { get; set; } 
    public virtual Exhibitor Exhibitor { get; set; } 

} 

public class Exhibitor 
{ 
    public int ExhibitorID { get; set; } 
    public string Company { get; set; } 
    public int StandID { get; set; } 
    public virtual Stand Stand { get; set; } 

} 

나는 확신을 그것은 모델의 "가상"부분과 관련이 있습니다.

아무도 연결을 허용하기 위해 업데이트해야 할 사항을 지적 할 수 있습니까?

마크

답변

5

EF는 주체 (상위)와 종속 (하위) 엔터티를 알지 못합니다. 먼저 엔터티 항목에 외래 키를 선언해야합니다. 주석 또는 유창한 매핑으로이 작업을 수행 할 수 있습니다.

public class Stand 
{ 
    [ForeignKey("Exhibitor")] 
    public int StandID { get; set; } 
    public string Description { get; set; } 
    public bool Booked { get; set; } 
    public int ExhibitorID { get; set; } 
    public virtual Exhibitor Exhibitor { get; set; } 

} 

유창함 매핑

0 :

using System.ComponentModel.DataAnnotations.Schema; 

다음 주석으로 Stand 클래스를 주석 :

주석

는 다음 네임 스페이스를 추가는 포함하도록 DbContext 클래스에 OnModelCreating 메서드를 재정의

:

modelBuilder.Entity<Stand>() 
    .HasOptional(s => s.Exhibitor) 
    .WithRequired(e => e.Stand); 
3

사용자가 만든 모델은 관계형 데이터베이스로 작업하는 것은 불가능합니다, 감사합니다. StandExibitorId이 필요하고 ExibitorStandId이 필요합니다. 순환 관계로 인해 두 테이블 중 하나에 행을 삽입 할 수 없습니다.

Exibitor이 하나 이상일 수 있고 Stand 인 관계를 1 대 다수로 변환하는 것이 하나의 옵션입니다.

public class Stand 
{ 
    public int StandID { get; set; } 
    public string Description { get; set; } 
    public bool Booked { get; set; } 
    public int? ExhibitorID { get; set; } 
    public virtual Exhibitor Exhibitor { get; set; }  
} 

public class Exhibitor 
{ 
    public int ExhibitorID { get; set; } 
    public string Company { get; set; } 
    public virtual ICollection<Stand> Stands { get; set; } 
} 

또는 공유 기본 키 매핑을 사용하여 일대일 관계를 만들 수 있습니다. 여기서 Stand은 주체입니다. ExibitorStandID을 PK로 사용합니다.

public class Stand 
{ 
    public int StandID { get; set; } 
    public string Description { get; set; } 
    public bool Booked { get; set; } 
    public virtual Exhibitor Exhibitor { get; set; } 
} 

public class Exhibitor 
{ 
    public int ExhibitorID { get; set; } 
    public string Company { get; set; } 
    public virtual Stand Stand { get; set; } 
} 

관계를 구성하는 데 Fluent API를 사용합니다.

modelBuilder.Entity<Exibitor>().HasRequired(e => e.Stand) 
    .WithOptional(s => s.Exibitor); 
관련 문제