Merge Key constraint with Entityframework

entity-framework-core

Question

I am a .NEt student trying to build a simple pizza webbshop. I am using Entityframework to build the database. The errormessage I get is this:

 The MERGE statement conflicted with the FOREIGN KEY constraint "FK_Products_Categories_CategoryID". The conflict occurred in database "TomasosPizzeria", table "dbo.Categories", column 'CategoryID'.
The statement has been terminated.

I have googled and tried to solve this pne alone by renaming the properties back and forth. Here are my classes:

public class Product
{
    public int ID { get; set; }
    public string ProductName { get; set; }
    public int ProductPrice { get; set; }
    public string Ingridients { get; set; }

    //--

    public List<OrderDetail> OrderDetails { get; set; }


    [ForeignKey("Categories")]
    public int CategoryID { get; set; }
    public virtual Category Categories { get; set; }
}




public class Category
    {
        public int CategoryID { get; set; }
        public string CategoryName { get; set; }

        List<Product> Products { get; set; }

    }

I am using a DbInitializer to set som test values. I have had problems giving the product object a category with the corresponding value.

 var categories = new Category[]
             {
                new Category{CategoryName="Pizza"},
                new Category{CategoryName="Pasta"},
                new Category{CategoryName="Sallad"},

             };


   var products = new Product[]
    {
        new Product{ProductName="Äcklig Calzone", Ingridients="Gamla tomater, möglig ost, trötta oliver, Unken skinka", ProductPrice=150},
        new Product{ProductName="Italiensk skit", Ingridients="Proscutti, halvfärdig mozzarella, trötta oliver, skämd vattnig proscutti", ProductPrice=250},
        new Product{ProductName="La bussola", Ingridients="Äckliga tomater, giftiga räkor, levande musslor, rutten skinka",CategoryID = 2,<--Here-- ProductPrice = 105 }


    };

    foreach (Product s in products)
    {
        context.Products.Add(s);
    }
    context.SaveChanges();

I am thankful for all the help I get. Please tell me if you wish to see any more of my code.

1
2
1/13/2017 1:29:50 PM

Accepted Answer

Solved it by giving CategoryID to the two other products.

2
1/13/2017 7:45:46 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow