【问题标题】:How to use a virtual property when initializing anonymous type Entity Framework初始化匿名类型实体框架时如何使用虚拟属性
【发布时间】:2018-10-26 01:54:08
【问题描述】:

当我尝试为我的数据库播种时,我使用的是这样的匿名类型:

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 VB.Net:Function(t) t.MyProperty。指定多个属性时使用匿名类型: C#: t => new { t.MyProperty1, t.MyProperty2 } VB.Net: `Function(t) New With { t.MyProperty1, t.MyProperty2 }

同样在阅读了这篇The properties expression is not valid. The expression should represent a property 之后,问题似乎是因为CalibrationSetupvirtual 属性。

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

【问题讨论】:

  • 你试过x => new { x.CalibrationSetup.Id, x.TargetIndex }吗?
  • @tschmit007 是的,使用它得到同样的错误
  • 所以 CalibrationSetup 是 CalibrationTarget 的子对象?在父级中公开 FK 并使用它 (CalibrationTarget.CalibrationSetup_Id)。
  • @SteveGreene CalibrationTarget 是 CalibrationSetup 的子对象

标签: c# entity-framework entity-framework-6 anonymous-types


【解决方案1】:

不看模型就很难工作,但是要播种 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,您可以简化。

【讨论】:

    猜你喜欢
    • 2013-01-24
    • 2014-09-14
    • 1970-01-01
    • 2016-05-29
    • 2017-07-28
    • 2012-08-04
    • 2012-01-22
    • 2011-11-22
    相关资源
    最近更新 更多