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

时间:2018-06-11 16:10:58

标签: c# sql-server asp.net-mvc entity-framework sql-insert

使用EF Code First迁移时,在数据库中创建包含代码的项时出错。

我已经在stackoverflow上回顾了几个与我的问题相似的QA,但它们并没有帮助我解决我的问题。所以请不要因为类似的问题而向我投票。我没有使用自动迁移。

我按照本教程http://mahedee.net/cascading-dropdown-list-in-asp-net-mvc-a-sample-demonstration/#comment-17847创建了MainCategories / SubCategories的级联下拉列表,它在我的列表中工作正常,但是当我创建一个Item时,我收到以下错误:

“INSERT语句与FOREIGN KEY约束冲突”FK_dbo.Fabrics_dbo.MainCategories_MainCategoryId“。冲突发生在数据库”MyFabricStashAppDb“,表”dbo.MainCategories“,列'MainCategoryId'。语句已被终止。”< / p>

我的模特如下: 我的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; }
    }
}

这是我的迁移类“Add-migration 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 - 我创建了这个来给View提供我所有类所需的所有属性。

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模型,因此我可以访问它们的属性。为简洁起见,我已经包含了索引操作和POST创建操作。

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中的行创建操作方法。

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

提前感谢您的帮助!我一直在研究这个问题,以找到解决方案。请好,这个论坛是为编程问题提供帮助,而不是被侮辱和羞辱!

2 个答案:

答案 0 :(得分:0)

Loooong问题,这是一种简化数据的方法。每个子类别都有唯一的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的listmodel。要显示,您将从Fabric.SubCategory1.MainCategory.MainCategoryId字段填充临时字段。因人而异。

答案 1 :(得分:0)

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

我只是添加了#34; MainCategoryId&#34;和&#34; SubCategory1Id&#34; POST Create操作方法中我的BIND语句的属性。请参阅下面的FabricController:

false

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