简体   繁体   中英

Entity Framework Error: The field “ForeignKey” is required EF

I have an entity setup as follows

public class ExampleObject
{
    [Key]
    public int ID { get; set; }
    public int RelationID { get; set; }
    public string SomeValue { get; set; }

    [ForeignKey("RelationID")]
    public virtual RelationObj RelationObj { get; set; }
}

Later in my project I use this entity as follows

foreach (var rec in allRecs)
{
    db.ExampleObject.Attach(rec);
    rec.SomeValue = "TEST"
}

db.SaveChanges();

This throws a DbEntityValidationException "The field "RelationObj" is required"

I don't want to include the RelationObj when loading these records, that affects performance. Why is EF bothering to check the foreign relation object? How do I go about fixing this?

First create the db, change the database on top of the script to match your db

USE [Breaz]
GO

/****** Object:  Table [dbo].[Relation]    Script Date: 6/29/2016 4:35:32 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Relation](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [RelatedSomeValue] [varchar](10) NULL,
 CONSTRAINT [PK_Relation] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

Then create the next table, again change the db (Breaz):

USE [Breaz]
GO

/****** Object:  Table [dbo].[Example]    Script Date: 6/29/2016 4:34:15 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Example](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [RelationID] [int] NOT NULL,
    [SomeValue] [varchar](10) NULL,
 CONSTRAINT [PK_Example] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[Example]  WITH CHECK ADD  CONSTRAINT [FK_Example_Relation] FOREIGN KEY([RelationID])
REFERENCES [dbo].[Relation] ([ID])
GO

ALTER TABLE [dbo].[Example] CHECK CONSTRAINT [FK_Example_Relation]
GO

Add a couple of rows of data into each table.

Add new item ADO.NET Entity Data Model, from your db and add both tables. Name the edmx ExampleModel. Get the (BreazEntities7) context (your context) from the Example.Context.cs file.

 public class HomeController : Controller
{
    public ActionResult YIndex()
    {
        using (BreazEntities7 db = new BreazEntities7())
        {
            var allRecs = db.Examples;
            foreach (var rec in allRecs)
            {
                rec.SomeValue = "TEST";
            }
            db.SaveChanges();
        }
        return View();
}

Here is the generated Example:

namespace Testy2.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Example
    {
        public int ID { get; set; }
        public int RelationID { get; set; }
        public string SomeValue { get; set; }

        public virtual Relation Relation { get; set; }
    }
}

Here id the generated Relation:

namespace Testy2.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Relation
    {
        public Relation()
        {
            this.Examples = new HashSet<Example>();
        }

        public int ID { get; set; }
        public string RelatedSomeValue { get; set; }

        public virtual ICollection<Example> Examples { get; set; }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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