Data in DbContext DbSet differs from database

I have a DbContext called ProjectContext which has DbSet

one called Cart which I pass values ​​to:

public class ShoppingCart
{
    ProjectContext _db = new ProjectContext();

    public void AddToCart(Video toAdd, Customer CurUser)
    {
        var CartItem = new Cart
        {
            CustomerID = CurUser.CustomerID,
            Item = toAdd.Title,
            Count = 1,
            Price = 1.00m
        };
        _db.Carts.Add(CartItem);
        _db.SaveChanges();

    }

}

public class Cart
{
    [Key, Required, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int CustomerID { get; set; }
    public string Item { get; set; }
    public int Count { get; set; }
    public decimal Price { get; set; }
}

      

Basically, a customer can have many different items in their shopping cart with the same CustomerID

. In a real database everything is fine and all the correct entries are added. The problem is that in the actual, the DbContext

first data record I insert for each client is repeated. So when I view the model in my view, the first record for each client just repeats, but for many real records there is one for this CustomerID

.

While debugging, you will notice that the bucket entries are indeed duplicated in DbSet

, even though they are not in the actual database.

I've never heard anything like it and really don't know what the problem is, so any help would be appreciated. Thanks in advance.

When I query the cart table in SQL Server I see the following:

5   shutter island  2   1.00
5   billy madison   2   1.00
5   superbad        1   1.00

      

When I browse in the view I see the following:

Item           Count     Price 
shutter island     2     1.00  
shutter island     2     1.00  
shutter island     2     1.00  

      

Code where I pass my model to view:

public ActionResult Index()
{
   IEnumerable model =(from r in _cartdb.Carts
            where r.CustomerID == WebSecurity.CurrentUserId
            select r);

   return View(model);
}

      

Code in view:

@model IEnumerable<MVCVideoProject.Models.Cart>
<table>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Item)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Count)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Price)
        </td>
        <td>
            @Html.ActionLink("Remove Item", "RemoveItem", new { custID = item.CustomerID, toRemove = item.Item })
        </td>
    </tr>
}
</table>

      

I can see when the debug I'm using DbSet

called Carts has duplicate entries, so I don't think the issue is the issue.

+3


source to share


1 answer


Your object Cart

must have a unique primary key. CustomerID

is not unique and EF always takes the first record it can find for one specific value. So I would introduce a field CartId

.



0


source







All Articles