【发布时间】:2020-01-26 11:40:51
【问题描述】:
我正在通过 MVC 中的回发进行实体更新:
ControlChartPeriod period = _controlChartPeriodService.Get(request.PeriodId);
if (period != null)
{
SerializableStringDictionary dict = new SerializableStringDictionary();
dict.Add("lambda", request.Lambda.ToString());
dict.Add("h", request.h.ToString());
dict.Add("k", request.k.ToString());
period.Parameters = dict.ToXmlString();
// ToDo : fails on save every now and then when one of the values changes; fails on Foreign Key being null
try
{
_controlChartPeriodService.Update(period, request.PeriodId);
return Ok(request);
}
更新方法如下:
public TObject Update(TObject updated, TKey key)
{
if (updated == null)
return null;
TObject existing = _context.Set<TObject>().Find(key);
if (existing != null)
{
_context.Entry(existing).CurrentValues.SetValues(updated);
_context.SaveChanges();
}
return existing;
}
public TObject Get(TKey id)
{
return _context.Set<TObject>().Find(id);
}
奇怪的是我第一次运行它时它通常运行良好;如果我进行第二次回发,它不起作用并且因外键的 EntityValidation 错误而失败;但是检查实体外键看起来很好并且没有受到影响。
我是否需要在某处同步上下文?
我一直在尝试找出成功与失败的区别。
我正在为存储库使用注入:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped((_) => new DataContext(ConfigSettings.Database.ConnectionString));
services.AddScoped<ControlChartPeriodService, ControlChartPeriodService>();
}
--更新:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public DateTime StartDate { get; set; }
public DateTime? EndDate { get; set; }
public virtual ICollection<ControlChartPoint> ControlChartPoints { get; set; }
[Required]
public virtual ControlChart ControlChart { get; set; }
public string Parameters { get; set; }
在 ControlChartMap 中,我们有以下内容:
HasMany(x => x.Periods)
.WithRequired(c => c.ControlChart);
【问题讨论】:
-
与问题无关,但我看到您将
ControlChartPeriodService添加到IServiceCollection作为实现和接口。应该是AddScoped<IControlChartPeriodService, ControlChartPeriodService>() -
谢谢,我已经以这种方式添加了所有存储库,因为我没有为它们创建接口。
-
“EntityValidation error of a foreign key”是什么意思?
-
表示周期的导航属性ControlChart不能为空;但是它不为空,因为它是作为实体动态加载的。
-
听起来是数据库上下文范围的问题
标签: c# entity-framework model-view-controller