2017-07-16 52 views
0

我在使用实体框架的Asp.net MVC中使用代码第一种方法。 我有购物车类,其中我使用2个不同的类,产品和UserProducts的对象。它们是虚拟对象,这意味着它们将被延迟加载使用。在一个类中延迟加载2个对象 - 其中一个被加载,另一个仍然为空

以下是我的三类:

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; } 
} 

问题是,产品的对象,当我从数据库加载车加载。但UserProducts对象不会加载并保留为空。以下是电话。我也尝试过。包括(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?

+1

是的,它是由EF命名约定引起的。参见[实体框架手册数据库更改](https://stackoverflow.com/questions/45016287/entity-framework-manual-database-change/45017334#45017334) - 相关问题的陈述不同,所以我不打算将其标记为重复,但答案也适用于您的问题。 –

+0

@TahirRauf你尝试使用“public int UserProductsId”而不是“public int UserProducts_Id” – hasan

回答

1

您可以尝试使用public int UserProductsId { get; set; }而不是
public int UserProducts_Id { get; set; }

当您将Id添加到主表的Entity Framework的classname中时,会自动将其视为外键。如果您使用ID为下划线实体框架将不会将其识别为外键属性。

public class Cart 
{ 
    [Key] 
    public int Id { get; set; } 
    public string CartId { get; set; } 
    public int ProductId { get; set; } 
    public int UserProductsId { 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; } 
} 
+0

谢谢 - 这工作。感谢您的快速概念。我在EF惯例中错过了它。 :) – TahirRauf

+0

欢迎:) – hasan

相关问题