简体   繁体   English

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

[英]Adding Data to Database (Error: System.Data.Entity.Infrastructure.DbUpdateException)

I am trying to insert input data from a Windows form into a database and get this error 我正在尝试将Windows窗体中的输入数据插入数据库中并出现此错误

System.Data.Entity.Infrastructure.DbUpdateException System.Data.Entity.Infrastructure.DbUpdateException

and when I checked the innerExeption I found this 当我检查innerExeption我发现了

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Tools_dbo.Locations_LocationId". INSERT语句与FOREIGN KEY约束“ FK_dbo.Tools_dbo.Locations_LocationId”冲突。 The conflict occurred in database "TMDatabase", table "dbo.Locations", column 'LocationId'. 数据库“ TMDatabase”的表“ dbo.Locations”的列“ LocationId”中发生了冲突。

But and kind of confuse course I did every thing right I think what is really the problem please Help with how to resolve it thank you 但是,有点混乱的过程,我做对了所有事情,我认为真正的问题是请帮助解决问题,谢谢

There as my models: 有我的模型:

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; }
}

I am using the Fluent API for my mapping and it goes like this 我正在使用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);
    }
}

This is my create button event handler code and am using a DTO for seeding into database 这是我的创建按钮事件处理程序代码,正在使用DTO植入数据库

The 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; }
}

The service that does the insert 进行插入的服务

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;
}

This is the the editable object that communicates with the Windows form 这是与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;
        }
    }
}

This is the create button event handler: 这是创建按钮事件处理程序:

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);
        }
}

Please help I don't really understand where the issue is coming from 请帮助我,我不太了解问题的根源

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;
}

In your dtoToEntity, you seem to be missing your locationId, which would cause it to give you this error. 在您的dtoToEntity中,您似乎缺少locationId,这将导致该错误。 Try inserting it in. 尝试将其插入。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 System.Data.Entity.Infrastructure.DbUpdateException - System.Data.Entity.Infrastructure.DbUpdateException System.Data.Entity.Infrastructure.DbUpdateException问题 - System.Data.Entity.Infrastructure.DbUpdateException Issue 将实体添加到数据库实体框架会生成异常&#39;System.Data.Entity.Infrastructure.DbUpdateException - Adding an entity to a database entity framework generates an exception 'System.Data.Entity.Infrastructure.DbUpdateException 发生System.Data.Entity.Infrastructure.DbUpdateException - System.Data.Entity.Infrastructure.DbUpdateException occurred MVC EF-System.Data.Entity.Infrastructure.DbUpdateException - MVC EF - System.Data.Entity.Infrastructure.DbUpdateException 如何解决 System.Data.Entity.Infrastructure.DbUpdateException - How to solve System.Data.Entity.Infrastructure.DbUpdateException 递归树方法上的System.Data.Entity.Infrastructure.DbUpdateException - System.Data.Entity.Infrastructure.DbUpdateException on recursive Tree method EntityFramework.dll 中发生“System.Data.Entity.Infrastructure.DbUpdateException” - 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll 如何避免System.Data.Entity.Infrastructure.DbUpdateException - How to avoid System.Data.Entity.Infrastructure.DbUpdateException 发生类型为“ System.Data.Entity.Infrastructure.DbUpdateException”的异常 - An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM