我想添加带外键的记录,以免写入数字ID。
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
我希望得到帮助,艾玛
答案 0 :(得分:1)
由于Id
尚未插入数据库,因此目前无法按Country
添加。您需要做的是设置{{1 Country
的属性被插入的新Fabricator
,当Country
插入数据库时,实体框架本身会在CountryId
上设置Fabricator
下面的代码应该会给你一些想法:
Fabricator
或者,您也可以按名称获取当地国家/地区(尚未添加),并将其分配给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
的{{1}}媒体资源。
Country