初始化匿名类型实体框架时如何使用虚拟属性



尝试为我的数据库播种时,我使用匿名类型,如下所示:

context.CalibrationTargets.AddOrUpdate(x => new { calId = x.CalibrationSetup.Id, targetIndex = x.TargetIndex },
new CalibrationTarget()...

但是CalibrationSetup是一个虚拟属性,我似乎得到了错误:

属性表达式x => new <>f__AnonymousType102(calId = x.CalibrationSetup.Id, targetIndex = x.TargetIndex)无效。表达式应表示一个属性:C#:t => t.MyPropertyVB.Net:Function(t) t.MyProperty。指定多个属性时,请使用匿名类型:C#:t => new { t.MyProperty1, t.MyProperty2 }VB.Net: 'Function(t( New with { t.MyProperty1, t.MyProperty2 }

同样在阅读这篇文章后,属性表达式无效。表达式应该表示一个属性,问题似乎是因为CalibrationSetup是一个virtual属性。

有没有办法解决这个问题,而不必用另一个virtual在匿名类型中使用的Calibration_Id列填充数据库?

如果不看到模型,很难工作,但要播种校准目标,您可能需要如下所示的内容。您的AddOrUpdate语法看起来也不对劲。你必须有已知的值,你将要播种。

context.CalibrationTargets.AddOrUpdate(
x => x.CalibrationTargetId,  // This is the field that determines uniqueness 
new CalibrationTarget
{
CalibrationTargetId = 1,  // if this is an identity column, omit and use a different field above for uniqueness
TargetIndex = 99,  // what value for target index? Fixed value or variable can be used
CalibrationSetup = new CalibrationSetup { Id = 77 }  // Same as above comment
},
new CalibrationTarget
{
CalibrationTargetId = 2,  // if this is an identity column, omit and use a different field above for uniqueness
TargetIndex = 88,  // what value for target index? Fixed value or variable can be used
CalibrationSetup = new CalibrationSetup { Id = 66 }  // Same as above comment
}
... repeat for all seeded records
);
context.SaveChanges();

如果 FK CalibrationSetupId 公开,您可以简化。