HasKey抛出InvalidOperationException - 这是Entity Framework Code First中的错误吗?

时间:2012-01-22 08:54:27

标签: entity-framework entity-framework-4.1 code-first

好的,我一直在这里看屏幕几个小时,不知道为什么我会收到这个错误。我在其他一些项目中使用过Code First,之前没有遇到任何问题...

这是错误:

System.InvalidOperationException was unhandled by user code
  Message=The properties expression 'sci => sci.ShoppingCartItemId' is not valid. The expression should represent a property: C#: 't => t.MyProperty'  VB.Net: 'Function(t) t.MyProperty'. When specifying multiple properties use an anonymous type: C#: 't => new { t.MyProperty1, t.MyProperty2 }'  VB.Net: 'Function(t) New From { t.MyProperty1, t.MyProperty2 }'.
  Source=EntityFramework
  StackTrace:
       at System.Data.Entity.ModelConfiguration.Utilities.ExpressionExtensions.GetSimplePropertyAccessList(LambdaExpression propertyAccessExpression)
       at System.Data.Entity.ModelConfiguration.EntityTypeConfiguration`1.HasKey[TKey](Expression`1 keyExpression)
       at BillingPlatform.DataLayer.BillingDb.OnModelCreating(DbModelBuilder modelBuilder) in [somepath]\BillingDb.cs:line 57
       at System.Data.Entity.Internal.LazyInternalContext.CreateModelBuilder()
       at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
       at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
  InnerException: 

这是抛出错误的代码。第一行:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{                       
   modelBuilder.Entity<ShoppingCartItem>().HasKey(sci => sci.ShoppingCartItemId);
   modelBuilder.Entity<Product>().HasKey<Guid>(p => p.ProductId);
   modelBuilder.Entity<DependentItemType>().HasKey<Guid>(dit => dit.DependentItemTypeId);
   modelBuilder.Entity<ProductCategory>().HasKey<Guid>(pc => pc.ProductCategoryId);

   base.OnModelCreating(modelBuilder);
}

以下是ShoppingCartItem类作为参考:

namespace BillingPlatform.Libraries
{
    public class ShoppingCartItem
    {
        /// <summary>
        /// The unique identifier of this shopping cart item.
        /// </summary>        
        public Guid ShoppingCartItemId { get; set; }

        public Product Product { get; set; }

        public decimal Price { get; set; }

        public decimal Tax { get; set; }

        public Guid UserId { get; set; }

        public bool InCart { get; set; }

        public string ProductData { get; set; }

        public DependentItemType DependentItemType { get; set; }

        public string DependentItemId { get; set; }
    }
}

有没有人理解为什么Entity Framework会抛出此错误?我的lambda表达式:

modelBuilder.Entity<ShoppingCartItem>().HasKey(s => s.ShoppingCartItemId);

非常简单。我不知道会出现什么问题......谢谢你能提出任何帮助!

2 个答案:

答案 0 :(得分:11)

好的问题是我的班级成员原本只是字段。 Code First需要 属性 。在进行代码更改和重建之后,我仍然遇到同样的错误。但是一旦Visual Studio被迫推送更新的DLL,一切都运行良好。

答案 1 :(得分:3)

这里不是这种情况(此处来自谷歌搜索),但如果HasKey使用定义其自己的字段名称的匿名类型,则可能还会发出这种确切的异常:

HasKey(t => new { KeyField1 = t.KeyField1, KeyField2 = t.KeyField2 });

应修好如下:

HasKey(t => new { t.KeyField1, t.KeyField2 });