gpt4 book ai didi

c# - Entity Framework FK 错误

转载 作者:太空宇宙 更新时间:2023-11-03 19:04:56 24 4
gpt4 key购买 nike

我的代码返回以下错误:

The property 'cartID' cannot be configured as a navigation property. The property must be a valid entity type and the property should have a non-abstract getter and setter. For collection properties the type must implement ICollection where T is a valid entity type.

我的模型如下:

[Table("ShoppingCarts")]
public class ShoppingCart
{
[Key]
public string cartID { get; set; }

public virtual ICollection<ShoppingCartItem> CartItems { get; set; }
public DateTime? DateCreated { get; set; }
public Guid UserID { get; set; }
}


[Table("ShoppingCartItems")]
public class ShoppingCartItem
{


private string cartDisplayImg;

[Key]
[Display(Name = "Cart Item ID#")]
public int cartItemID { get; set; }

[Display(Name = "Cart ID")]
[ForeignKey("cartID")]
public string cartID { get; set; }
[Required]
public string itemTitle { get; set; }

public int listingID { get; set; }
public int sellerID { get; set; }
[Required]
public string sellerSKU { get; set; }
[Required]
public int Quantity { get; set; }
public string itemType { get; set; }

public string condition { get; set; }
[Required]
public decimal Price { get; set; }

public string Make { get; set; }
public string Model { get; set; }
public string displayImgPath
{

get {
cartDisplayImg = "http://www.example.com/Images/Phones/" + Make + "-" + Model + "-1.jpg";

return cartDisplayImg;

}

}
public decimal lineTotal
{
get {
decimal cartLineTotal = Price * Quantity;
return cartLineTotal;
}

}

}

public class ShopingCartContext : DbContext
{

public ShopingCartContext()
: base("PHONEOUTLET_DBConnectionString")
{
Database.SetInitializer<ShopingCartContext>(new CreateDatabaseIfNotExists<ShopingCartContext>());

}


public DbSet<ShoppingCart> ShoppingCart { get; set; }
public DbSet<ShoppingCartItem> ShoppingCartItems { get; set; }
}

最佳答案

ForeignKey必须在 FK 属性上使用数据注释以及告诉它哪个导航属性表示它是外键的关系的信息:

[Table("ShoppingCartItems")]
public class ShoppingCartItem
{
//..
[Display(Name = "Cart ID")]
[ForeignKey("Shoppingcart")]
public string cartID { get; set; }
public virtual ShoppingCart Shoppingcart { get; set; }
}

或者,您可以将 ForeignKey 注释应用于导航属性,并告诉它哪个属性是关系的外键:

[Table("ShoppingCartItems")]
public class ShoppingCartItem
{
//..
[Display(Name = "Cart ID")]
public string cartID { get; set; }

[ForeignKey("cartID")]
public virtual ShoppingCart Shoppingcart { get; set; }
}

此外,Code First 有一组 rules用于在发现关系时定位外键属性。约定基于属性的名称。如果将外键属性命名为 [Target Type Key Name][Target Type Name] + [Target Type Key Name],则将按照惯例发现外键属性>[导航属性名称] + [目标类型键名]。如果您使用 ForeignKey 数据注释,这些规则将被忽略,因为您明确地告诉 EF 您想要使用什么 FK 属性。

关于c# - Entity Framework FK 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29656579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com