繁体   English   中英

错误-INSERT语句与FOREIGN KEY约束冲突

[英]Error - The INSERT statement conflicted with the FOREIGN KEY constraint

使用EF Code First迁移时,在数据库中用代码创建项目时出现错误。

我已经检查了与我的问题类似的关于stackoverflow的几个QA,但是它们并不能帮助我解决问题。 我没有使用自动迁移。

我按照本教程http://mahedee.net/cascading-dropdown-list-in-asp-net-mvc-a-sample-demonstration/#comment-17847创建了MainCategories / SubCategories的级联下拉列表,并且在我的列表,但是当我创建一个项目时,出现以下错误:

INSERT语句与FOREIGN KEY约束“ FK_dbo.Fabrics_dbo.MainCategories_MainCategoryId”冲突。 数据库“ MyFabricStashAppDb”的表“ dbo.MainCategories”的列“ MainCategoryId”中发生了冲突。 该语句已终止。

我的模型如下:My MainCategory.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyFabricStashApp.Models
{
    public class MainCategory
    {
        public int MainCategoryId { get; set; }
        public string Name { get; set; }
        public List<SubCategory1> SubCategories1 { get; set; }

    }
}

我的SubCategory1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace MyFabricStashApp.Models
{
    public class SubCategory1
    {
        public int SubCategory1Id { get; set; }
        public string Name { get; set; }
        public int MainCategoryId { get; set; }
        public virtual MainCategory MainCategory { get; set; }

    }
}

我的Fabric.cs(项目类)

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace MyFabricStashApp.Models
{
    public class Fabric
    {
        public int FabricId { get; set; } //Item Number

        public int MainCategoryId { get; set; }
        public virtual MainCategory MainCategory { get; set; }

        public int SubCategory1Id { get; set; }
        public virtual SubCategory1 SubCategory1 { get; set; }
        public string Name { get; set; }
        public string ImagePath { get; set; }
        public string Location { get; set; }
        public string Type { get; set; } //Knit, Woven, Voile, Interfacing, Denim, Suiting, etc.
        public string Weight { get; set; }//Lightweight, Medium, Heavy
        public string Content { get; set; }//Cotton, Polyester, Nylon, etc.
        public string Design { get; set; }//Marvel Comics, Amy Butler, etc.
        public string Brand { get; set; } //Springs Creative Products, Free Spirit, Robert Kaufman, etc.
        public double Quantity { get; set; }//.25 yd, .50 yd, .75 yd, 1.0 yd, etc.
        public int Width { get; set; }// in inches, ie. 44", 54", etc.
        public string Source { get; set; }//Joann
        public string Notes { get; set; }
        public List<string> Tags { get; set; }
        public int ItemsSold { get; set; }
        public virtual ICollection<Purchase> Purchases { get; set; }
    }
}

这是我的迁移课程“添加迁移FirstMigration”

namespace MyFabricStashApp.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class FirstMigration : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.Fabrics",
                c => new
                    {
                        FabricId = c.Int(nullable: false, identity: true),
                        MainCategoryId = c.Int(nullable: false),
                        SubCategory1Id = c.Int(nullable: false),
                        Name = c.String(),
                        ImagePath = c.String(),
                        Location = c.String(),
                        Type = c.String(),
                        Weight = c.String(),
                        Content = c.String(),
                        Design = c.String(),
                        Brand = c.String(),
                        Quantity = c.Double(nullable: false),
                        Width = c.Int(nullable: false),
                        Source = c.String(),
                        Notes = c.String(),
                        ItemsSold = c.Int(nullable: false),
                    })
                .PrimaryKey(t => t.FabricId)
                .ForeignKey("dbo.MainCategories", t => t.MainCategoryId, cascadeDelete: false)
                .ForeignKey("dbo.SubCategory1", t => t.SubCategory1Id, cascadeDelete: false)
                .Index(t => t.MainCategoryId)
                .Index(t => t.SubCategory1Id);

            CreateTable(
                "dbo.MainCategories",
                c => new
                    {
                        MainCategoryId = c.Int(nullable: false, identity: true),
                        Name = c.String(),
                    })
                .PrimaryKey(t => t.MainCategoryId);

            CreateTable(
                "dbo.SubCategory1",
                c => new
                    {
                        SubCategory1Id = c.Int(nullable: false, identity: true),
                        Name = c.String(),
                        MainCategoryId = c.Int(nullable: false),
                    })
                .PrimaryKey(t => t.SubCategory1Id)
                .ForeignKey("dbo.MainCategories", t => t.MainCategoryId, cascadeDelete: false)
                .Index(t => t.MainCategoryId);

            CreateTable(
                "dbo.Purchases",
                c => new
                    {
                        PurchaseId = c.Int(nullable: false, identity: true),
                        PurchaseDate = c.DateTime(nullable: false),
                        PurchaseQuantity = c.Int(nullable: false),
                        PurchasePrice = c.Double(nullable: false),
                        FabricId = c.Int(nullable: false),
                    })
                .PrimaryKey(t => t.PurchaseId)
                .ForeignKey("dbo.Fabrics", t => t.FabricId, cascadeDelete: false)
                .Index(t => t.FabricId);

        }

        public override void Down()
        {
            DropForeignKey("dbo.Fabrics", "SubCategory1Id", "dbo.SubCategory1");
            DropForeignKey("dbo.Purchases", "FabricId", "dbo.Fabrics");
            DropForeignKey("dbo.Fabrics", "MainCategoryId", "dbo.MainCategories");
            DropForeignKey("dbo.SubCategory1", "MainCategoryId", "dbo.MainCategories");
            DropIndex("dbo.Purchases", new[] { "FabricId" });
            DropIndex("dbo.SubCategory1", new[] { "MainCategoryId" });
            DropIndex("dbo.Fabrics", new[] { "SubCategory1Id" });
            DropIndex("dbo.Fabrics", new[] { "MainCategoryId" });
            DropTable("dbo.Purchases");
            DropTable("dbo.SubCategory1");
            DropTable("dbo.MainCategories");
            DropTable("dbo.Fabrics");
        }
    }
}

我的FabricListViewModel.cs-创建此文件的目的是使“视图”访问所有类中所需的所有属性。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyFabricStashApp.Models
{
    public class FabricListViewModel
    {
        public int FabricId { get; set; } //Item Number

        public int MainCategoryId { get; set; }
        public string MainCategoryName { get; set; }

        public int SubCategory1Id { get; set; }
        public string SubCategory1Name { get; set; }

        public string Name { get; set; }
        public string ImagePath { get; set; }
        public string Location { get; set; }
        public string Type { get; set; } //Knit, Woven, Voile, Interfacing, Denim, Suiting, etc.
        public string Weight { get; set; }//Lightweight, Medium, Heavy
        public string Content { get; set; }//Cotton, Polyester, Nylon, etc.
        public string Design { get; set; }//Marvel Comics, Amy Butler, etc.
        public string Brand { get; set; } //Springs Creative Products, Free Spirit, Robert Kaufman, etc.
        public double Quantity { get; set; }//.25 yd, .50 yd, .75 yd, 1.0 yd, etc.
        public int Width { get; set; }// in inches, ie. 44", 54", etc.
        public string Source { get; set; }//Joann
        public string Notes { get; set; }
        public int ItemsSold { get; set; }
        public int PurchaseCount { get; set; }

    }
}

在我的控制器FabricController中,您可以看到我在List中包含MainCategory和SubCategory1模型,因此我可以访问它们的属性。 为了简洁起见,我包括了Index操作和POST Create操作。

public class FabricController : Controller
    {
        private MyFabricStashDb db = new MyFabricStashDb();

        // GET: Fabric
        public ActionResult Index(string searchTerm = null)
        {
            var model = db.Fabrics.Include(f => f.MainCategory).Include(f => f.SubCategory1)
                .OrderByDescending(f => f.ItemsSold)
                .Where(f => searchTerm == null || f.Name.StartsWith(searchTerm))
                .Select(f => new FabricListViewModel
                {
                    FabricId = f.FabricId,
                    Name = f.Name,
                    MainCategoryId = f.MainCategoryId,
                    MainCategoryName = f.MainCategory.Name,
                    SubCategory1Id = f.SubCategory1Id,
                    SubCategory1Name = f.SubCategory1.Name,
                    ImagePath = f.ImagePath,
                    Location = f.Location,
                    Type = f.Type,
                    Weight = f.Weight,
                    Content = f.Content,
                    Design = f.Design,
                    Brand = f.Brand,
                    Quantity = f.Quantity,
                    Width = f.Width,
                    Source = f.Source,
                    Notes = f.Notes,
                    ItemsSold = f.ItemsSold,
                    PurchaseCount = f.Purchases.Count()
                });
            return View(model);
        }
// POST: Fabric/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "FabricId,MainCategory,SubCategory1,SubCategory2,Name,ImagePath,Location,Type,Weight,Content,Design,Brand,Quantity,Width,Source,Notes,ItemsSold")] Fabric fabric, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                var filename = Path.GetFileName(file.FileName);
                string fabricId = fabric.FabricId.ToString();
                string myfile = fabricId + "_" + filename;
                var path = Path.Combine(Server.MapPath("~/images"), myfile);
                fabric.ImagePath = myfile;
                file.SaveAs(path);
                db.Fabrics.Add(fabric);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(fabric);
        }

我需要在POST Create方法中绑定MainCategory和SubCategory1类的属性吗? 难道这就是为什么INSERT语句失败的原因? 在“ db.SaveChanges();”上失败 POST Create操作方法中的一行。

当我注释掉这些public virtual MainCategory MainCategory {get; set;} public virtual MainCategory MainCategory {get; set;}属性,它可以工作,并且我可以创建一个新的Item,但是我无法在FabricController中包含这些类,因为该属性在Fabric类中不存在,因此我无法访问它们的属性。

笨拙的问题,这是一种简化数据的方法。 每个子类别都有唯一的ID。 要链接到主要类别,可以通过结构所属的子类别进行选择。 那给了我们

public class Fabric
    {
        public int FabricId { get; set; } //Item Number

        // public int MainCategoryId { get; set; }
        // public virtual MainCategory MainCategory { get; set; }

        public int SubCategory1Id { get; set; }
        public virtual SubCategory1 SubCategory1 { get; set; }
        public string Name { get; set; }
        public string ImagePath { get; set; }
        public string Location { get; set; }
        public string Type { get; set; } //Knit, Woven, Voile, Interfacing, Denim, Suiting, etc.
        public string Weight { get; set; }//Lightweight, Medium, Heavy
        public string Content { get; set; }//Cotton, Polyester, Nylon, etc.
        public string Design { get; set; }//Marvel Comics, Amy Butler, etc.
        public string Brand { get; set; } //Springs Creative Products, Free Spirit, Robert Kaufman, etc.
        public double Quantity { get; set; }//.25 yd, .50 yd, .75 yd, 1.0 yd, etc.
        public int Width { get; set; }// in inches, ie. 44", 54", etc.
        public string Source { get; set; }//Joann
        public string Notes { get; set; }
        public List<string> Tags { get; set; }
        public int ItemsSold { get; set; }
        public virtual ICollection<Purchase> Purchases { get; set; }
    }

只要您通过以下方式检索Fabric

db.Fabrics.Include("SubCategory1").Include("SubCategory1.MainCategory").FirstOrDefault(p => p.FabricId == <something>);

您可以引用Fabric.SubCategory1.MainCategory.Name

使用MainCategory / SubCategory1填充下拉列表,并确保在创建时将SubCategory1键放入Fabric记录中。 应该简化你的生活。 您的下拉列表将绑定到MainCategory的临时字段和SubCategory1.SubCategoryId的列表模型。 为了显示,您将从Fabric.SubCategory1.MainCategory.MainCategoryId字段填充临时字段。

我将解决方法发布到这里。 上面的@juharr和@ user1011627在评论中回答了该问题,但我想发布解决方案,以防有人遇到相同的问题。

我只是在POST Create操作方法的BIND语句中添加了“ MainCategoryId”和“ SubCategory1Id”属性。 参见下文,在FabricController中:

// POST: Fabric/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "FabricId,MainCategory,MainCategoryId, SubCategory1Id,SubCategory1,SubCategory2,Name,ImagePath,Location,Type,Weight,Content,Design,Brand,Quantity,Width,Source,Notes,ItemsSold")] Fabric fabric, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                var filename = Path.GetFileName(file.FileName);
                string fabricId = fabric.FabricId.ToString();
                string myfile = fabricId + "_" + filename;
                var path = Path.Combine(Server.MapPath("~/images"), myfile);
                fabric.ImagePath = myfile;
                file.SaveAs(path);
                db.Fabrics.Add(fabric);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(fabric);
        }

我敢肯定还有其他方法可以做到这一点,但这对我来说是使其与应用程序中其他代码一起使用的最简单,最快的解决方案。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM