实体框架一对多:SqlException

时间:2018-07-24 09:01:06

标签: entity-framework one-to-many

当我尝试使用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时的表“国家/地区”

预先感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

GetColumnDefinition属性添加到CountryId类中,并在添加新的Site集时使用Site而不是CountryId属性

Country

答案 1 :(得分:0)

您在这里使用上下文有一个小问题。您已经使用一个DBContext实例加载国家(将跟踪该国家对象的国家),然后使用另一个DBContext来保存该站点(其中第一个国家对象是一个属性)。

最好使用一个数据库上下文(将在您的类之间共享)对单个工作单元执行所有操作,并且有责任将其处置在存储库层之外进行处理。