实体框架dbSet.Add当挂钩类 [英] Entity Framework dbSet.Add when classes linked

查看:129
本文介绍了实体框架dbSet.Add当挂钩类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

:结果
为什么没有 dbSet.Add 当我尝试添加的链接到其他对象EF对象方法的工作?

Question:
Why doesn't the dbSet.Add method work when I'm attempting to add an object that's linked to other objects in EF?

详情:结果
在这一些背景:我与EF一个初学者,我正在学习如何使用code首先开发的数据模型。

Details:
Some background on this: I'm a beginner with EF, and I'm learning how to use Code First to develop the data model.

我使用VS2013前preSS,实体框架6通过的NuGet添加到基本MVC项目。

I'm using VS2013 Express, with Entity Framework 6 added through NuGet to a basic MVC project.

我已经创建了三个班我的数据模型: Class_oneOnly Class_many Class_several Class_oneOnly 有一个一对多的关系,其他两个类,以及其他两个类都彼此多对一对多的关系。

I've created three classes for my data model: Class_oneOnly, Class_many, and Class_several. Class_oneOnly has a one-to-many relationship to the other two classes, and the other two classes have a many-to-many relationship to each other.

我使用code第一,但求解释的关系而言,这里是一个实体关系图(我在一个单独的项目吸引了这一点,所以有code-第一和模型首先之间没有干扰。此外,没有pre-产生code ...虽然也许我应该去的方式,我想学习code在前):结果

I'm using Code First, but for purposes of explaining the relationships, here's an entity relationship diagram (I drew this in a separate project, so there's no interference between Code-First and Model-First. Also, there is no pre-generated code...although perhaps I should have gone that way, I'm trying to learn Code First):

我可以创建每个类的新实例。

I can create new instances of each class.

然而,当我尝试执行的 DbSet.Add 方法添加 class_many 到数据库中,我得到一个错误的NullReferenceException是由用户code未处理。

However, when I try to perform the DbSet.Add method to add a new instance of class_many to the database, I get an error "NullReferenceException was unhandled by user code."

这是真的,我不要在try-catch块都没有了。的但是,即使有try-catch块,它仍然无法解释的异常的:结果
型System.NullReferenceException'的例外发生在EF测试code First.dll但在用户code没有处理其他信息:未将对象引用设置的一个实例对象。

This is true, I don't have this in a try-catch block. But, even with a try-catch block, it still wouldn't explain the exception:
"An exception of type 'System.NullReferenceException' occurred in EF Test Code First.dll but was not handled in user code. Additional information: Object reference not set to an instance of an object."

的主要问题是:为什么说空引用被抛出,如果所有三个班在这一点上已经确定不应该EF照顾分配属性的类是在code首先定义的关系联系在一起?

The main question is: Why is it that a null reference is being thrown, if all three classes at this point have been defined? Shouldn't EF take care of assigning properties to classes that are linked by relationships defined in Code First?

我要补充的东西到我的code,使这项工作?

Should I add something to my code to make this work?

code例子:结果
设置的EF DbSet:

Code Examples:
Setting up the EF DbSet:

using System.Data.Entity;

namespace EF_Test_Code_First.Models
{
    public class Context : DbContext
    {
        public Context()
            : base("name=MyContext")
        {
        }

        public DbSet<Class_many> Class_manys { get; set; }
    }
}

类定义:

public class Class_oneOnly
{
    [Key]
    public string SN { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Class_many> Class_manys { get; set; }
    public virtual ICollection<Class_several> Class_severals { get; set; }
}

public class Class_several
{
    public int ID { get; set; }
    public string Name { get; set; }

    public Class_oneOnly Class_oneOnly { get; set; }
    public virtual ICollection<Class_many> Class_manys { get; set; }
}

public class Class_many
{
    public int ID { get; set; }
    public string Name { get; set; }

    public virtual Class_oneOnly Class_oneOnly { get; set; }
    public virtual ICollection<Class_several> Class_severals { get; set; }
}

......,最后但并非最不重要的,我的测试code,设置了类并尝试使用DbSet.Add方法。 上下文的DbContext 从控制器传递(并且是一个静态上下文,如上面的类中定义):

...and, last but not least, my test code that sets up the classes and attempts to use DbSet.Add method. Context dbContext is passed from the controller (and is a static Context, as defined in the class above):

public void myTest(Context dbContext)
{
    /* assign property values to oneOnly,
        * of which there is only one of these
        * in each many and each several.
        */

    Class_oneOnly oneOnly = new Class_oneOnly()
    {
        SN = "1",
        Name = "oneOnly1"
    };

    /* make sure ids are unique as the following
        * 'for' loop is iterated through
        */
    int startid;
    if (dbContext.Class_manys != null && dbContext.Class_manys.Count() > 0){
        startid = dbContext.Class_manys.Count();
    }
    else{
        startid = 0;
    }

    /* create and fill class_many and
        * class_several objects, using a new id.
        */
    for (int i = startid; i < 5; i++)
    {
        /* assign property values to many
            * and several.
            */
        Class_many many = new Class_many()
        {
            ID = i,
            Name = "many" + i.ToString()
        };

        Class_several several = new Class_several()
        {
            ID = i,
            Name = "several" + i.ToString()
        };

        /* assign further property values
            * that use navigation properties
            * to link between classes.
            */
        many.Class_oneOnly = oneOnly;
        several.Class_oneOnly = oneOnly;
        many.Class_severals.Add(several);

        /* add to EF
            */
        /*************************
            * Error occurs at this line
            *************************
            */
        dbContext.Class_manys.Add(many);
    }

    /* save
        */
    dbContext.SaveChanges();
}

我可以从请求项目的其他部分提供code。

I can provide code from other parts of the project on request.

推荐答案

对,所以我重新创建项目,并想我找到了问题。第一件事:我会建议使用您的DbContext的的静态的,而是在使用块。如果你还有问题,那就是我所做的尝试和解决,什么我总是尝试做。我想你会发现它很难后来追查的问题,如果你已经有了一个全球性的,静态的环境。

Right, so I re-created your project and think I found the issue. First thing: I would recommend using your DbContext NOT as static, but rather in a using block. If you still have problems, that's what I did to try and troubleshoot, and what I always try to do. I think you will find it harder to track down problems later on if you've got a global, static context.

我打空引用错误many.Class_severals.Add(几个); ,而不是在那里你说你没有。我没有使用一个快速的WinForms项目来解决,但我不知道为什么/如果你正在使用code上面贴......总之,你将如何得到一个不同的错误,你有两个选择:你需要创建一个新的集合,如果它尚未初始化,您可以在吸气的构造或(我的preference)做到这一点。

I hit a null reference error on many.Class_severals.Add(several); instead of where you said you did. I did use a quick Winforms project to troubleshoot, but I'm not sure why/how you would get a different error if you're using the code posted above... Anyhow, you have two options: you need to create a new collection if it's not already initialized, and you can do it in a constructor or (my preference) in the getter.

public class Class_many
    {
        public int ID { get; set; }
        public string Name { get; set; }

        private ICollection<Class_several> _severals;

        public virtual Class_oneOnly Class_oneOnly { get; set; }
        public virtual ICollection<Class_several> Class_severals { get
        {
            return _severals ?? new List<Class_several>();
        }
            set { _severals = value; }
        }
    }

这篇关于实体框架dbSet.Add当挂钩类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆