0

EF6 코드를 먼저 수행하고 내 프로젝트에 맞게 약간 수정하려고했지만 데이터베이스를 시드 할 때 문제가 발생했습니다. 초기화 자.EF6 이니셜 라이저 및 일대 다 ICollection을 통해 시딩

나는이 개 수업을 만들었습니다

프로퍼티 모드 :

namespace MyApp.Models 

{ 
    public class Property 
    { 
     public int ID { get; set; } 
     public string PropertyName { get; set; } 

     public virtual PropertyType PropertyType { get; set; } 
    } 
} 

및 특성 유형 모드 :

namespace MyApp.Models 
{ 
    public class PropertyType 
    { 
     public int ID { get; set; } 
     public string Type { get; set; } 

     public ICollection<Property> Properties { get; set; } 
    } 
} 

나의 이해는 있다는 것입니다 일대 관계가 있습니다. 2. 속성은 속성 유형이 1 개일 수 있지만 많은 속성이 동일한 속성 유형을 가질 수 있습니까? 내가 컨텍스트를 초기화하고 (아래의 코드를 사용하여) 데이터베이스를 시드 할 때

그러나, 나는 오류 얻을 :

public class MyAppInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<MyAppContext> 
{ 
    protected override void Seed(MyAppContext context) 
    { 
     var propertytypedata = new List<PropertyType> 
     { 
      new PropertyType {ID = 1, Type="Villa" }, 
      new PropertyType {ID = 2, Type="Apartment" } 
     }; 

     propertytypedata.ForEach(p => context.PropertyType.Add(p)); 
     context.SaveChanges(); 

     var propertydata = new List<Property> 
     { 
      new Property {PropertyName="Property 1", PropertyType=1, } 
     }; 

     propertydata.ForEach(p => context.Property.Add(p)); 
     context.SaveChanges(); 
    } 
} 

문제는,이다 것을 나는의 속성 유형을 설정하려고 할 때 나는 파종하고있는 재산, 그것은 말한다 :

Cannot implicitly convert type 'int' to 'MyApp.Models.PropertyType'

+0

'PropertyType = 1,'. PropertyType은 정수가 아닌 복합 객체입니다. –

답변

1

예 :

protected override void Seed(MyAppContext context) 
    { 
     var propertytypedata = new List<PropertyType> 
     { 
      new PropertyType {ID = 1, Type="Villa" }, 
      new PropertyType {ID = 2, Type="Apartment" } 
     }; 

     foreach(var propertyType in propertytypedata){     
      propertyType.Properties = new List<Property> 
      { 
       new Property {PropertyName="Property 1", PropertyType = propertyType, } 
      }; 
      context.PropertyType.Add(propertyType) 
     } 

     context.SaveChanges(); 
    } 

당신은이 개 해부가 필요하지 않습니다 e가 더합니다. Entity Framework에서 하위 컬렉션을 데이터베이스에 추가합니다. 해당 속성 유형에 액세스 할 때마다 ICollection<Property> Propertiesvirtual으로 표시하면 하위 모음으로 속성이 이미로드됩니다. 그렇지 않으면로드 할 때 include()이 필요합니다.