2017-05-10 5 views
0

숫자 ID를 쓰지 않으려면 외래 키가있는 레코드를 추가하고 싶습니다.외래 키가있는 시드의 레코드 추가 Entity Framework

protected override void Seed(ClockShopEntities context) 
    { ... } // Seed 

    private void AddType(ClockShopEntities context) 
    { 
     context.Typs.Add(new Typ { typName = "name1" }); 
     context.Typs.Add(new Typ { typName = "name2" }); 
    } // AddType 

    private void AddCountry(ClockShopEntities context) 
    { 
     context.Countries.Add(new Country { countryName = "country1" }); 
     context.Countries.Add(new Country { countryName = "country2" }); 
     context.Countries.Add(new Country { countryName = "country3" }); 
     context.Countries.Add(new Country { countryName = "country4" }); 
    } // AddCountry 

어떻게 이름을 지정하여 값을 추가 할 수 있습니까? 내가 도움을 희망

// !!!!! with write id 
    private void AddFabricator(ClockShopEntities context) 
    { 
     context.Fabricators.Add(new Fabricator { fName = "", idCountry = 1 }); 
    } // AddFabricator 


    // How can I write without Id 
    private void AddFabricator(ClockShopEntities context) 
    { 
     context.Fabricators.Add(
      new Fabricator { fName = "", idCountry = ?? where Country = "country1" }); 
    } // AddFabricator 

, 엠마

답변

1

당신은 Country이 때 Id으로 추가 할 수 없습니다 아직 데이터베이스에 삽입되지 않았습니다. 대신 Country 속성을 으로 설정하면 새로운 Country이 삽입되고 엔터티 프레임 워크는 Fabricator이 데이터베이스에 삽입 될 때 Fabricator에서 CountryId으로 설정됩니다. 이름으로 (즉, 아직 추가되지 않은)

private void AddCountry(ClockShopEntities context) 
{ 
    var country1 = new Country { countryName = "country1" }; 
    AddFabricator(context, country1); 
    context.Countries.Add(country1); 

    context.Countries.Add(new Country { countryName = "country2" }); 
    context.Countries.Add(new Country { countryName = "country3" }); 
    context.Countries.Add(new Country { countryName = "country4" }); 
} // AddCountry 

private void AddFabricator(ClockShopEntities context, Country country) 
{ 
    context.Fabricators.Add(new Fabricator { fName = "", Country = country }); 
} // AddFabricator 

또는, 당신은 또한 지역의 나라를 얻을 수 있습니다 및 FabricatorCountry 속성에 그 지정 :

다음이 코드는 몇 가지 아이디어를 줄 것이다.

private void AddFabricator(ClockShopEntities context) 
{ 
    context.Fabricators.Add(new Fabricator { fName = "", Country = context.Countries.First(c => c.countryName == "country1") }); 
} // AddFabricator 
+0

암시 적으로 'string'유형을 'bool'유형으로 변환 할 수 없습니다. 블록의 일부 반환 형식이 대리자 반환 형식으로 암시 적으로 변환되지 않기 때문에 람다 식을 대리자 형식으로 변환 할 수 없습니다. –

+0

업데이트 된 코드를 확인하고, 조건에서 등호를 놓쳤습니다. – sachin

+0

예! 고마워. –