ASP NET MVC Core 2 with entity framework saving primery key Id to column that isnt a relationship column

asp.net-core-mvc entity-framework-core foreign-keys

Question

Please look at this case: enter image description here

    if (product.ProductId == 0)
    {
        product.CreateDate = DateTime.UtcNow;
        product.EditDate = DateTime.UtcNow;

        context.Products.Add(product);

        if (!string.IsNullOrEmpty(product.ProductValueProduct)) { SaveProductValueProduct(product); }
    }
        context.SaveChanges();

When I debug code the ProductId is negative, but afer save the ProductId is corect in database (I know this is normal), but when I want to use it here: SaveProductValueProduct(product) after add to context.Products.Add(product); ProductId behaves strangely. (I'm creating List inside SaveProductValueProduct)

    List<ProductValueProductHelper> pvpListToSave = new List<ProductValueProductHelper>();
    foreach (var item in dProductValueToSave)
    {
        ProductValueProductHelper pvp = new ProductValueProductHelper();
        pvp.ProductId = (item.Value.HasValue ? item.Value : product.ProductId).GetValueOrDefault();
        pvp.ValueId = Convert.ToInt32(item.Key.Remove(item.Key.IndexOf(",")));
        pvp.ParentProductId = (item.Value.HasValue ? product.ProductId : item.Value);
        pvpListToSave.Add(pvp);
    }

I want to use ProductId for relationship. Depends on logic I have to save ProductId at ProductId column OR ProductId at ParentProductId column.

enter image description here

The ProductId 45 save corent at ProductId column (3rd row - this is a relationship), BUT not at ParentProductId (2nd row - this is just null able int column for app logic), although while debug I pass the same negative value from product.ProductId there.

QUESTION: how can I pass correct ProductId to column that it isn't a relationship column

1
0
8/6/2018 3:32:49 AM

Popular Answer

I just use SaveProductValueProduct(product) after SaveChanges (used SaveChanges twice)

    if (product.ProductId == 0)
    {
        product.CreateDate = DateTime.UtcNow;
        product.EditDate = DateTime.UtcNow;
        context.Products.Add(product);
    }
    context.SaveChanges();

    if (product.ProductId != 0)
    {
        if (!string.IsNullOrEmpty(product.ProductValueProduct)) { SaveProductValueProduct(product); }
        context.SaveChanges();
    }

I set this as an answer because it fixes the matter, but I am very curious if there is any other way to solve this problem. I dont like to use context.SaveChanges(); one after another.

0
8/6/2018 3:46:40 AM


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