繁体   English   中英

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

[英]How to use a virtual property when initializing anonymous type Entity Framework

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

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.MyProperty 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列填充数据库?

在不查看模型的情况下很难工作,但是要播种CalibrationTargets,您可能需要以下类似的东西。 您的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,则可以简化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM