首页 > 解决方案 > C#, ASP.NET MVC, Entity Framework : relationship multiplicity constraint violation

问题描述

I am having some issues trying to find out exactly where this issue is taking place. I have a Cart where Parts are put in. When I try to view the cart, I get this error. I have reviewed a bunch of other posts on this matter and they all seem to be related to ForeignKeys Or the way they are written in EntityTypeConfiguration. The issue is I do not have any of these.

I do my joins in models and occasionally I will use `[ForeignKey("")] in a model. The thing is I do not have any of this in this particular instance.. This code worked before. I have made some changes, however the changes I have made are not on the code for this view.

Here is the controller code:

public ActionResult Index()
{
   var cart = ShoppingCart.GetCart(this.HttpContext);

   // Set up our ViewModel
   var viewModel = new ShoppingCartViewModels
   {
      CartItems = cart.GetCartItems(),
      CartTotal = cart.GetTotal()
   };

    // Return the view
    return View(viewModel);
}

Here is the GetCart:

string ShoppingCartId { get; set; }

public const string CartSessionKey = "CartId";

public static ShoppingCart GetCart(HttpContextBase context)
{
   var cart = new ShoppingCart();
   cart.ShoppingCartId = cart.GetCartId(context);
   return cart;
}

// Helper method to simplify shopping cart calls
public static ShoppingCart GetCart(Controller controller)
{
   return GetCart(controller.HttpContext);
}

Here is the CartItems:

public List<Cart> GetCartItems()
{
  return storeDB.Carts.Where(cart => cart.CartId == ShoppingCartId).ToList();
}

Here is the Cart.cs:

public class Cart
{
    [Key]
    public int RecordId { get; set; }
    public string CartId { get; set; }
    public Guid Material { get; set; }
    public string Class { get; set; }
    public int Count { get; set; }

    [Display(Name = "Created")]
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = false)]
    public System.DateTime DateCreated { get; set; }

    //public virtual Parts Parts { get; set; }
    public virtual ExtParts EParts { get; set; }

    public bool IsDelete { get; set; }
}

This is CartTotal:

public decimal GetTotal()
{
   decimal? total = (from cartItems in storeDB.Carts
                     where ((cartItems.CartId == ShoppingCartId) && (cartItems.Class != "MACH") || ( cartItems.Class != "PRT"))                        
                     select (int?)cartItems.Count * cartItems.EParts.SellingPrice).Sum() ?? 0;

   decimal? total2 = (from cartItems in storeDB.Carts
                     where ((cartItems.CartId == ShoppingCartId) && (cartItems.Class == "MACH") || (cartItems.Class == "PRT"))
                     select (int?)cartItems.Count * cartItems.EParts.MachinedPrice).Sum() ?? 0;

   decimal? totals = total + total2;

   return totals ?? decimal.Zero;
}

And here is the ExtParts.cs which is actually a SQL Server view:

public class ExtParts
{
    [Key]
    [Display(Name = "Part")]
    public Guid Material { get; set; }

    [Display(Name = "Drawing")]
    public string DrawingNumber { get; set; }

    [Display(Name = "Description")]
    [DataType(DataType.MultilineText)]      
    public string Description { get; set; }

    [Display(Name = "Ext Desc")]
    [DataType(DataType.MultilineText)]
    public string ExtDescription { get; set; }

    [Display(Name = "Image")]
    public string PartImage { get; set; }

    public bool ShowPrice { get; set; }

    [Display(Name = "Part #")]
    public string PartNumber { get; set; }

    [Display(Name = "Stock")]
    public int? UnitsInStock { get; set; }

    [UIHint("_Status")]
    public bool? Status { get; set; }

    [Display(Name = "Created")]
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = false)]
    public DateTime? CreatedDate { get; set; }

    [Display(Name = "Created By")]
    public string CreatedBy { get; set; }

    public Guid VendorId { get; set; }

    [Display(Name = "Vendor Ref")]
    public string VendorRef { get; set; }

    [Display(Name = "UOM")]
    public string UnitOfMeasure { get; set; }

    [Display(Name = "Updated")]
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = false)]
    public DateTime? UpdatedDate { get; set; }
    public string UpdatedBy { get; set; }
    public bool? IsDelete { get; set; }
    public string MakeOrBuy { get; set; }
    public string Class { get; set; }
    public decimal SellingPrice { get; set; }
    public decimal MachinedPrice { get; set; }
    public decimal LastCost { get; set; }

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

Here is the SQL Server view statement that is used for the ExtParts.cs:

SELECT        
    dbo.Parts.Material, dbo.Parts.DrawingNumber, 
    dbo.Parts.Description, dbo.Parts.ExtDescription, 
    dbo.Parts.PartImage, dbo.Parts.UnitsInStock, 
    dbo.Parts.Status, dbo.Parts.CreatedDate, 
    dbo.Parts.CreatedBy, dbo.Parts.UpdatedDate, dbo.Parts.UpdatedBy, 
    dbo.Parts.IsDelete, 
    dbo.Parts.PartNumber, dbo.Parts.Class, dbo.Parts.MakeOrBuy, 
    dbo.Parts.ShowPrice, dbo.ProductMaster.SellingPrice, 
    dbo.ProductMaster.LastCost, dbo.ProductMaster.MachinedPrice, 
    dbo.ProductMaster.VendorRef, dbo.ProductMaster.UnitOfMeasure, 
    dbo.ProductMaster.VendorId
FROM
    dbo.Parts 
INNER JOIN
    dbo.ProductMaster ON dbo.Parts.Material = dbo.ProductMaster.Material

This is the model that is used for the View:

public class ShoppingCartViewModels
{
    public List<Cart> CartItems { get; set; }
    public decimal CartTotal { get; set; }
}

I know this is a lot of code to look at but I wanted to put as much as i could since i do not know where it is happening.. Thank you for your help!

I will be happy to show more code if needed.

I think i know where this is happening. ExtParts returns 2 records, these records are different Vendors for the same Part. Providing that i am fetching these from the table with the id of the part and not the vendor, it causes it to pull 2 exact records. I will check it out further and Let everyone know..

标签: c#sql-serverasp.net-mvcentity-framework

解决方案


推荐阅读