INSERT与外键冲突

时间:2019-04-08 03:05:22

标签: c# asp.net .net asp.net-mvc entity-framework

对不起,如果我打扰您了,但是我正在学习Entity Framework,看来我遇到了一个简单的问题,每次尝试添加新产品时都会出现。

  

INSERT语句与FOREIGN KEY约束“ FK_Products_Categories_CategoryId”冲突。数据库“ prueba1”的表“ dbo.Categories”的列“ Id”中发生了冲突。该声明已终止。

我正在阅读Pro Entity Framework Core 2本书,并且按照与示例相同的步骤进行操作,但是我无法弄清楚如何解决此问题,还检查了Microsoft Relationships文档,好像那里没有错误。

Product.cs

public class Product
{
    public long Id { get; set; }

    public string Name { get; set; }
    public decimal PurchasePrice { get; set; }
    public decimal RetailPrice { get; set; }

    public long CategoryId { get; set; }
    public Category Category { get; set; }
}

Category.cs

public class Category
{
    public long Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

编辑 :这是我将产品添加到数据库并在控制器上调用它的功能(我正在使用存储库模式btw)。

public class DataRepository : IRepository
    {
        private DataContext context;

        public DataRepository(DataContext ctx) => context = ctx;

        public void AddProduct(Product product)
        {
            context.Products.Add(product);
            context.SaveChanges();
        }
   }

0 个答案:

没有答案