将数据添加到数据库(错误:System.Data.Entity.Infrastructure.DbUpdateException)

时间:2014-07-07 07:58:43

标签: c# asp.net winforms service dto

我正在尝试将Windows窗体中的输入数据插入到数据库中并获得此错误

  

System.Data.Entity.Infrastructure.DbUpdateException

当我查看innerExeption时,我发现了这个

  

INSERT语句与FOREIGN KEY约束冲突" FK_dbo.Tools_dbo.Locations_LocationId"。冲突发生在数据库" TMDatabase",table" dbo.Locations",column' LocationId'中。

但是有点混淆当然我做的每一件事都是正确的我觉得什么是真正的问题请帮助解决它如何解决它谢谢你

我的模特:

public class Tools : BaseEntity
{
    public int ToolId { get; set; }
    public string Name { get; set; }
    public string Serial { get; set; }
    public int Quantity { get; set; }
    public bool IsCalibarted { get; set; }
    public DateTime DueDate { get; set; }
    public string Discription { get; set; }
    public byte[] Image { get; set; }

    //Reference Mapping
    public int LocationId { get; set; }
    public virtual Locations Locations { get; set; }
}

public class Locations : BaseEntity
{
    public int LocationId { get; set; }
    public string LocationCode { get; set; }
    public string LocationName { get; set; }
    public string Discription { get; set; }

    public virtual ICollection<Tools> Tools { get; set; }
}

我正在使用Fluent API进行映射,它就像这样

public class ToolsEntityConfig : EntityTypeConfiguration<Tools>
{
    public ToolsEntityConfig()
    {
        this.HasKey(t => t.ToolId);
        this.Property(t => t.Name).IsRequired();
        this.Property(t => t.Serial).IsRequired();
        this.Property(t => t.Quantity).IsRequired();
        this.Property(t => t.DueDate).IsOptional();
        this.Property(t => t.Discription).IsOptional();

        this.HasRequired(t => t.Locations)
            .WithMany(t => t.Tools)
            .HasForeignKey(t => t.LocationId)
            .WillCascadeOnDelete(false);
    }
}

这是我的创建按钮事件处理程序代码,我正在使用DTO播种到数据库

DTO

public class ToolsDTO
{
    public ToolsDTO()
    {
    }

    public ToolsDTO(Tools tools)
    {
        this.ToolId = tools.ToolId;
        this.Name = tools.Name;
        this.Serial = tools.Serial;
        this.Quantity = tools.Quantity;
        this.DueDate = tools.DueDate;
        this.IsCalibrated = tools.IsCalibarted;
        this.Discription = tools.Discription;
        this.Image = tools.Image;

        //this.CategoryId = tools.CategoryId;
        this.LocationId = tools.LocationId;
        //this.LayerId = tools.LayerId;
        //this.SupplyId = tools.SupplyId;
    }

    public int ToolId { get; set; }
    public string Name { get; set; }
    public string Serial { get; set; }
    public int Quantity { get; set; }
    public DateTime DueDate { get; set; }
    public string Discription { get; set; }
    public bool IsCalibrated { get; set; }
    public byte[] Image { get; set; }

    //Reference Mapping
    public int CategoryId { get; set; }
    public int LocationId { get; set; }
    public int LayerId { get; set; }
    public int SupplyId { get; set; }
}

执行插入的服务

public ToolsDTO CreateTools(ToolsDTO tool)
{
        var tools = dtoToEntity(tool);
        UoW.Tools.Add(tools);
        UoW.Commit();

        return new ToolsDTO(tools);
}

private Tools dtoToEntity(ToolsDTO tool)
{
        var addtool = new Tools
        {
            ToolId = tool.ToolId,
            Name = tool.Name,
            Serial = tool.Serial,
            Quantity = tool.Quantity,
            DueDate = tool.DueDate,
            Discription = tool.Discription
        };

        return addtool;
}

这是与Windows窗体

通信的可编辑对象
public class ToolsObject : ToolsDTO, IEditableObject 
{
    private ToolsObject _OriginalObject;
    private bool _Editing;

    public ToolsObject(int Id, string serial, string name, int quantity, DateTime duedate, string desc, int locId)
    {
        this.ToolId = Id;
        this.Serial = serial;
        this.Name = name;
        this.Quantity = quantity;
        this.DueDate = duedate;
        this.Discription = desc;
        this.LocationId = locId;
    }

    public ToolsObject(int Id, string serial, string name, int quantity, DateTime duedate, bool IsCalib, string desc, byte[] image, int locId)
    {
        this.ToolId = Id;
        this.Serial = serial;
        this.Name = name;
        this.Quantity = quantity;
        this.DueDate = duedate;
        this.Discription = desc;
        this.IsCalibrated = IsCalib;
        this.Image = image;
        this.LocationId = locId;
    }

    public ToolsObject()
    {
    }

    public void BeginEdit()
    {
        if (!_Editing)
        {
            _Editing = true;
            _OriginalObject = this.MemberwiseClone() as ToolsObject;
        }
    }

    public void CancelEdit()
    {
        if (_Editing)
        {

            this.Name = _OriginalObject.Name;
            this.Serial = _OriginalObject.Serial;
            this.Quantity = _OriginalObject.Quantity;
            this.DueDate = _OriginalObject.DueDate;
            this.Discription = _OriginalObject.Discription;
            this.IsCalibrated = _OriginalObject.IsCalibrated;
            this.Image = _OriginalObject.Image;
            this.CategoryId = _OriginalObject.CategoryId;
            this.LocationId = _OriginalObject.LocationId;
            this.SupplyId = _OriginalObject.SupplyId;

            _Editing = false;
        }
    }

    public void EndEdit()
    {
        if (_Editing)
        {
            _Editing = false;
            _OriginalObject = null;
        }
    }
}

这是创建按钮事件处理程序:

private void AddTool()
{
        MemoryStream ms1 = new MemoryStream();

        this.ptbTools.Image.Save(ms1, ImageFormat.Jpeg);

        try
        {
            ToolsObject newtool = new ToolsObject();

            if (String.IsNullOrWhiteSpace(this.txtToolName.Text) || String.IsNullOrWhiteSpace(this.txtSerial.Text) || this.txtQuantity.Value == 0 || this.cmbLocation.SelectedItem == null)
            {
                MessageBox.Show("All fields with (*) are required");
                return;
            }

            if (this.chbCalib.Checked == true)
            {
                if (this.dtpCalibrateDate.Value == DateTime.Today)
                {
                    MessageBox.Show("Set Calibration Due-Date");
                    return;
                }
                this.chbCalib.Checked = true;
                newtool.IsCalibrated = true;
            }
            else if (!this.chbCalib.Checked)
            {
                this.chbCalib.Checked = false;
                newtool.IsCalibrated = false;
                dtpCalibrateDate.Value = DateTime.Now;
            }

            var selectedLocationId = ((LocationObject)cmbLocation.SelectedItem).LocationId;

            newtool.Name = this.txtToolName.Text;
            newtool.Serial = this.txtSerial.Text;
            newtool.Quantity = (int)this.txtQuantity.Value;
            newtool.LocationId = selectedLocationId;
            newtool.Discription = this.txtDescription.Text;
            newtool.IsCalibrated = this.chbCalib.Checked;
            newtool.DueDate = this.dtpCalibrateDate.Value;
            newtool.Image = ms1.ToArray();

            var tool = toolService.CreateTools(newtool);

            MessageBox.Show(string.Format("You have successfully created {0} tool", tool.Name));

            toolsList.Add(new ToolsObject(tool.ToolId, tool.Serial, tool.Name, tool.Quantity, tool.DueDate, tool.IsCalibrated, tool.Discription, tool.Image, tool.LocationId));

            bsTools.ResetBindings(true);
            bsTools.ResumeBinding();

            ToggleUI(UIMode.Initial);

        }
        catch (InvalidOperationException ex)
        {
            MessageBox.Show(ex.Message);
        }
}

请帮助我真正了解问题的来源

1 个答案:

答案 0 :(得分:0)

private Tools dtoToEntity(ToolsDTO tool)
{
        var addtool = new Tools
        {
            ToolId = tool.ToolId,
            Name = tool.Name,
            Serial = tool.Serial,
            Quantity = tool.Quantity,
            DueDate = tool.DueDate,
            Discription = tool.Discription
        };

        return addtool;
}

在你的dtoToEntity中,你似乎错过了你的locationId,这会导致它给你这个错误。尝试将其插入。

private Tools dtoToEntity(ToolsDTO tool)
{
    var addtool = new Tools
    {
        ....
        LocationId = tool.LocationId,
        ....
    };
    return addtool;
}