实体框架代码中首先要求的外键

时间:2013-09-19 19:12:36

标签: c# entity-framework ef-code-first

我正在为电子商务项目开发代码,

我有2个类:类别和产品

关系是一对多,类别有很多产品, 我想根据需要创建外键(不为null),因此,如果我添加产品,我必须输入categoryid。

当我这样做时,我收到此错误:

  

在表'Products'上引入FOREIGN KEY约束'FK_dbo.Products_dbo.Categories_categoryId'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。

有什么想法吗?

public class Category :IObjectWithState
{
    [Key]
    public int CategoryId { get; set; }
    [Required]
    public string Discription { get; set; }
    public string Notes { get; set; }
    public int ParentCategoryId { get; set; }

    public virtual ICollection<Product> Products { get; set; }
    public virtual ICollection<Discount> Discounts { get; set; }
    public virtual ICollection<ProductList> ProductLists { get; set; }

    [NotMapped]
    public State state { get; set; }
}

public class Product :IObjectWithState
{
    [Key]
    public int ProductId { get; set; }
    [Required]
    public string ProductName { get; set; }
    [Required]
    public string ShortDiscription { get; set; }
    public string LongDiscription { get; set; }

     [Required]
    public bool Active { get; set; }

    [Required]
    public int categoryId { get; set; }
    [ForeignKey("categoryId")]
    public  Category Category { get; set; }

    public ICollection<ProductImage> ProductImage { get; set; }
    public ICollection<Discount> Discount { get; set; }
    public ICollection<Discussion> Duscussion { get; set; }
    public ICollection<ProductAttributeValue> ProductAttributeValue { get; set; }
    public ICollection<ProductListItem> ProductListItem { get; set; }
    public ICollection<ProductSKU> ProductSKU { get; set; }
    public ICollection<RelatedProduct> RelatedProduct { get; set; }
    public ICollection<Review> Review { get; set; }
    public ICollection<ShoppingCart> ShoppingCart { get; set; }
}

1 个答案:

答案 0 :(得分:0)

我在迁移类

中将cascadeDelete:设置为false