【发布时间】:2017-10-21 16:07:17
【问题描述】:
我有两个用 EF CodeFirst 编写的表:
public class DayType
{
[Key]
public int DayTypeID { get; set; }
public string NameDayType { get; set; }
public virtual ICollection<SpecialDay> Specialdays { get; set; }
public DayType() { }
}
public class SpecialDay
{
[Key]
public int SpecialDayID { get; set; }
public int Year { get; set; }
public int JanuaryDay { get; set; }
public SpecialDay() { }
public int? DayTypeId { get; set; }
public virtual DayType daytype { get; set; }
}
DBContext 的一对多关系是由 FluentAPI 实现的:
modelBuilder.Entity<DayType>().HasMany(p => p.Specialdays).WithOptional(p => p.daytype);
此代码抛出异常。函数的目的是更新实体。调试时sd 具有所有属性。 sd - 是从数据网格中选择然后更改的对象。
internal void Update(SpecialDay sd)
{
using (SalDBContext _db = new SalDBContext())
{
var newsd = _db.SpecialDays.FirstOrDefault(p => p.SpecialDayID==sd.SpecialDayID);
newsd.JanuaryDay = sd.JanuaryDay;
....
newsd.DecemberDay = sd.DecemberDay;
newsd.DayTypeId = sd.DayTypeId;
newsd.daytype = sd.daytype;
try
{
_db.SaveChanges();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
此时发生异常_db.SaveChanges();Exception:
{“无法定义两个对象之间的关系,因为它们附加到不同的ObjectContext对象。”} System.Exception {System.InvalidOperationException}
感谢您为我的问题提供解决方案的任何帮助。谢谢
【问题讨论】:
标签: c# entity-framework ef-code-first