当我尝试使用EntityFramework将项目保存到数据库中时,我遇到了一个小问题。
我的课程如下:
public partial class Site
{
public int Id { get; set; }
public string Name { get; set; }
public string LongName { get; set; }
public string Adress { get; set; }
public City City { get; set; }
public Country Country { get; set; }
public string VATNumber { get; set; }
}
public class Country
{
public int CountryId { get; set; }
public string Name { get; set; }
public string IsoCode { get; set; }
}
当我尝试在控制器中创建新站点时,它可以工作,但是当我尝试添加指向现有国家/地区的链接时:
if (SiteProvider.GetSiteByName(Site.Name) == null)
{
Site.Country = CountryProvider.GetCountryById(1);//it's working, i see the link to the right country
SiteProvider.Create(Site);
}
public static void Create(Site Site)
{
using (MyDBContext Context = new MyDBContext())
{
Context.Site.Add(Site);
Context.SaveChanges(); //here is the problem
}
}
我收到此错误:
SqlException:无法为身份列插入显式值 IDENTITY_INSERT设置为OFF时的表“国家/地区”
预先感谢您的帮助。
答案 0 :(得分:0)
将GetColumnDefinition
属性添加到CountryId
类中,并在添加新的Site
集时使用Site
而不是CountryId
属性
Country
答案 1 :(得分:0)
您在这里使用上下文有一个小问题。您已经使用一个DBContext实例加载国家(将跟踪该国家对象的国家),然后使用另一个DBContext来保存该站点(其中第一个国家对象是一个属性)。
最好使用一个数据库上下文(将在您的类之间共享)对单个工作单元执行所有操作,并且有责任将其处置在存储库层之外进行处理。