简体   繁体   English

实体框架:一个或多个外键属性不可为空

[英]Entity Framework: one or more of the foreign-key properties is non-nullable

I have a very complex database model.我有一个非常复杂的数据库模型。 My program computes some data+db entries and modifies+generates new entries to update+insert in the database.我的程序计算一些data+db entriesmodifies+generates new entries以更新+插入数据库。

When I use database context to insert the entries, everything works.当我使用数据库上下文插入条目时,一切正常。 But when I try to save changes:但是当我尝试保存更改时:

{"The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted."} {"操作失败:无法更改关系,因为一个或多个外键属性不可为空。对关系进行更改时,相关外键属性将设置为空值。如果外键不支持空值,必须定义新关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象。"}

I have seen too many questions on SO about this topic.我已经看到太多关于这个主题的问题。 But my problem is that the model is so complex that I cannot track the issue.但我的问题是模型太复杂了,我无法跟踪问题。 Entity Framework 6 is not giving me any information about the source of the problem, relationship name, ... Entity Framework 6 没有给我任何关于问题根源、关系名称、...

Is there a way to get more help from Entity Framework in order to find the source of the problem?有没有办法从 Entity Framework 获得更多帮助以找到问题的根源?

You have to analyze your object to solve this problem.你必须分析你的对象来解决这个问题。

Here some simple code to explain your Exception :这里有一些简单的代码来解释您的Exception

static void Main()
{
    using (MyDbContext ctx = new MyDbContext())
    {
        // Build a new object
        MyClass o = new MyClass() { Id = 1, ChildObject = null };

        // Add it to your Context (It's not in the DB yet!)
        ctx.MyObjects.Add(o);

        // Write all changes (the new object) to the Db
        ctx.SaveChanges();
    }
}

// You got some DbContext with a DbSet pointing to your Table "MyTable"
public class MyDbContext : DbContext
{
    public DbSet<MyClass> MyObjects { get; set; }
}

// You've got a class to map your table to some nice object.
[Table("MyTable")]
public class MyClass
{
    // Some column..
    [Key]
    public int Id { get; set; }

    // And some ForeignKey! Which maps a column with the Id to an object.
    [ForeignKey("ChildObjectId")]
    public MyClass ChildObject { get; set; }
}

In this example i create a Context add an object and save the changes (create an Insert to the table).在这个例子中,我创建了一个上下文添加一个对象并保存更改(创建一个插入到表中)。

1st: The Exception occurs at SaveChanges, because the Property "ChildObject" can be set to null, becuase we don't have any restrictions on that property.第一:异常发生在 SaveChanges,因为属性“ChildObject”可以设置为 null,因为我们对该属性没有任何限制。

2nd: The Exception is a Db-Exception.第二:异常是数据库异常。 Your Program is (probably) runnging correct.您的程序(可能)运行正确。 But qour Db tells you, that it is not allowed to have a row in MyTable without a reference to a ChildObject.但是 qour Db 告诉您,在没有对 ChildObject 的引用的情况下,不允许在 MyTable 中有一行。

You have to question yourself if the db is configured wrong (Make the column nullable) or if your program forgets to set the child.如果数据库配置错误(使列可以为空),或者您的程序是否忘记设置子项,您必须自问。

I hope you see: You have to dig in your code.我希望你看到:你必须挖掘你的代码。 You got a problem with your 'complet model' and you have to solve it.你的“完整模型”有问题,你必须解决它。

Consider reading the SQL-Log of the context.考虑阅读上下文的 SQL-Log。 Example: ctx.Log = Console.WriteLine;示例: ctx.Log = Console.WriteLine; (Don't have a Studio here, but i think i should be something like this). (这里没有工作室,但我想我应该是这样的)。

This way you can grab the last SQL-Query and run it on your Db for better error-outputs.通过这种方式,您可以获取最后一个 SQL-Query 并在您的数据库上运行它以获得更好的错误输出。

Issue is occurring because referenced table values are associated to the main table directly inside the c# object of Main table出现问题是因为引用的表值直接与主表的 c# 对象内的主表相关联

CREATE TABLE [dbo].[MainTable](
            [MainId] [int],
            [Name] [varchar](50) NOT NULL
);

CREATE TABLE [dbo].[ReferedTable](
            [ReferId] [int],
            [MainId] [int] NOT NULL,
            [Name] [varchar](50) NULL
);

And there is constraint on the foreign key并且对外键有约束

using (EF context = new EF())
{
        var values = context.MainTable.Include("ReferedTable");
        var referedValues = values.ReferedTable.ToList();

        foreach (var value in referedValues)
        {
            context.ReferedTable.DeleteObject(value);
        }
        context.SaveChanges();
}

If you try to do below, then error will come.如果您尝试执行以下操作,则会出现错误。 Because ReferedTable is connected to Main table and if you do changes in it and save, EF will throw error因为 ReferedTable 连接到 Main 表,如果您对其进行更改并保存,EF 将抛出错误

using (EF context = new EF())
{
        var values = context.MainTable.Include("ReferedTable");
        var referedValues = values.ReferedTable.ToList();

        foreach (var value in referedValues)
        {
            values.ReferedTable.Remove(value);
        }
        context.SaveChanges();
}

I manually went recursively for each child of my object doing this procedure:我手动递归执行此过程的对象的每个子项:

if(parent.child!=null){
    parent.childId=parent.child.id;
    parent.child=null;
}

By this way you remove every child object from parent and just leave the Id, so EntityFramework does not make any wrong insertion and it is still conscient that the relationships exist.通过这种方式,您从父对象中删除每个子对象并只保留 Id,因此 EntityFramework 不会进行任何错误插入,并且仍然有意识地存在这些关系。

暂无
暂无

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

相关问题 实体框架5无法更改该关系,因为一个或多个外键属性不可为空 - Entity Framework 5 The relationship could not be changed because one or more of the foreign-key properties is non-nullable 实体框架无法更改关系,因为一个或多个外键属性不可为空 - Entity Framework The relationship could not be changed because one or more of the foreign-key properties is non-nullable 尝试更新实体框架中的记录无法更改关系,因为一个或多个外键属性不可为空 - Trying to update record in entity framework The relationship could not be changed because one or more of the foreign-key properties is non-nullable EF添加实体:由于一个或多个外键属性不可为空,因此无法更改关系 - EF adding entity: The relationship could not be changed because one or more of the foreign-key properties is non-nullable 编辑实体时出错:由于一个或多个外键属性不可为空,因此无法更改关系 - While editing entity getting error: The relationship could not be changed because one or more of the foreign-key properties is non-nullable 删除实体时我得到以下错误:由于一个或多个外键属性不可为空,因此无法更改关系 - When Deleting Entity I get an Error of: The relationship could not be changed because one or more of the foreign-key properties is non-nullable 由于一个或多个外键属性不可为空,因此无法更改该关系 - The relationship could not be changed because one or more of the foreign-key properties is non-nullable Pocos-无法更改关系,因为一个或多个外键属性不可为空 - Pocos - The relationship could not be changed because one or more of the foreign-key properties is non-nullable 操作失败:由于一个或多个外键属性不可为空,因此无法更改该关系asdf - The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable, asdf “由于一个或多个外键属性不可为空,因此无法更改关系”-但不能删除任何内容 - “The relationship could not be changed bc one or more of the foreign-key properties is non-nullable” - But not deleting anything
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM