好的,我一直盯着屏幕几个小时了,但是我不知道为什么会出现这个错误。我在其他项目中使用了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 class)的参考代码:
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);
这非常简单。我不知道哪里出了问题...感谢您能提供的任何帮助!
ShoppingCartItemId
不是属性而只是公共字段,我可以重现异常,但在您的示例中它是一个属性。我能想象到您有另一个名为ShoppingCartItem
的类型。请确保在您的模型构建器中使用BillingPlatform.Libraries.ShoppingCartItem
。因为这应该可以工作。 - nemesv