【发布时间】:2017-07-16 09:44:06
【问题描述】:
我在使用实体框架的 Asp.net MVC 中使用代码优先方法。 我有 Cart 类,我在其中使用 2 个不同类的对象,即 Product 和 UserProducts。它们是虚拟对象,这意味着它们将被延迟加载使用。
以下是我的三个课程:
public class Cart
{
[Key]
public int Id { get; set; }
public string CartId { get; set; }
public int ProductId { get; set; }
public int UserProducts_Id { get; set; }
public int Count { get; set; }
public System.DateTime DateCreated { get; set; }
public virtual Product Product { get; set; }
public virtual UserProducts UserProducts { get; set; }
}
[Table("dbo.Product")]
public class Product
{
[Key]
public int ProductID { get; set; }
public int ProductTypeID { get; set; }
public string Name { get; set; }
public string SKU { get; set; }
public string Description { get; set; }
public string SpecTitle { get; set; }
public decimal Price { get; set; }
//public Int16 Published { get; set; }
public bool Deleted { get; set; }
public int SiteId { get; set; }
public int UserId { get; set; }
}
[Table("dbo.UserProducts")]
public class UserProducts
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int ArtworkId { get; set; }
public int ProductId { get; set; }
public decimal ProductPrice { get; set; }
public string ProductDescription { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public string ModifiedBy { get; set; }
public DateTime? ModifiedOn { get; set; }
public bool IsActive { get; set; }
public string ArtworkPath { get; set; }
public int UserId { get; set; }
public int SiteId { get; set; }
}
问题是,当我从数据库加载购物车时会加载 Product 对象。但 UserProducts 对象不会加载并保持为空。以下是通话。我也试过 .Include(p => p.UserProducts),但它也不起作用。
storeDB.Carts.Where(
cart => cart.CartId == ShoppingCartId).ToList();
这是否与 EF 的 Id 命名约定有关? bcz Product 类的 PK 作为 ProductId,在 Cart 类中,它的 FK 也被命名为 ProductId。但是对于 UserProducts,该 calss 的 PK 仅命名为 Id,而在 Cart 类 FK 中命名为 UserProducts_Id?
【问题讨论】:
-
是的,它是由 EF 命名约定引起的。请参阅Entity Framework manual Database Change - 相关问题的表述方式不同,因此我不会将其标记为重复,但答案也适用于您的问题。
-
@TahirRauf 您是否尝试使用“public int UserProductsId”而不是“public int UserProducts_Id”
标签: c# asp.net-mvc database entity-framework ef-code-first