无法将重复值插入唯一索引。 [表名=项目,约束名称= PK_dbo.Items]

时间:2014-01-24 18:01:35

标签: c# wpf entity-framework sql-server-ce

当我在我的entityframework中添加LtPartStock对象时,我收到此错误我已尽可能搜索它但我无法在此处获得解决方案是我的代码

class Item
{

    [Key, Column(Order = 0)]
    public string type { get; set; }
    public string remark { get; set; }
}
 [Table("LtPart")]
class LtPart : Item
{
    [NotMapped]
    public string partNo { get{
        return type;
    }
        set
        {
            type = value;
        }
    }
    [Key,Column(Order = 1)]
    public string serialNo { get; set; }
    public LtPart(string partNo,string serialNo)
    {
        this.type = partNo;
        this.serialNo = serialNo;
    }
    public void Add(string partyName, string invoiceNo, int quantity, Double amount,            DateTime date,Company company)
    {
        LTPartImportRecord record = new LTPartImportRecord(this, quantity, partyName, amount, invoiceNo, date, company);
        using (var db = new StoreHelper())
        {
            db.LtParts.Add(this);
            db.ltpartImportRecords.Add(record);
            db.SaveChanges();
        }
        LTPartStock.addToStock(quantity, this,company);
    }
}
abstract class Stock
{   [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int stockId { get; set; }
    public int available { get; set; }
    public int consumed { get; set; }
    public int companyId { get; set; }
    [ForeignKey("companyId")]
    public Company company { get; set; }
}
class LTPartStock : Stock {
     [ForeignKey("part")]
    public string serialNo { get; set; }

    public LtPart part { get; set; }
    public static void addToStock(int quantity,LtPart part,Company company)
    {
        using(var db=new StoreHelper()){
            db.ltpartStock.Load();
            var stocks = from stock in db.ltpartStock
                        where stock.part.type == part.partNo && stock.part.serialNo == part.serialNo
                        select stock;
        bool updated = true;
        foreach (var stock in stocks)
        {

            stock.available += quantity;

            updated = false;
        }
        if (updated)
        {

            db.ltpartStock.Add(new LTPartStock {companyId=1,
                available = quantity, serialNo = part.serialNo, consumed = 0 ,part=part});

        }
        db.SaveChanges();
    }

    }
}

这里我们称之为函数

LtPart part = new LtPart(partNoCombo.Text.Trim(),
            serialNoText.Text.Trim()
            )
        ;
        part.Add(partyNameCombo.Text.Trim(), invoiceNoText.Text.Trim(), int.Parse(quantityText.Text.Trim()), double.Parse(amountText.Text.Trim()), dateText.DisplayDate, (Company)companyCombo.SelectedItem);

我得到了这个例外

EntityFramework.dll中发生未处理的“System.Data.Entity.Infrastructure.DbUpdateException”类型异常 附加信息:更新条目时发生错误。有关详细信息,请参阅内部异常  帮助我,我不知道该怎么做,谢谢。

0 个答案:

没有答案