为什么我必须为Code First / Entity Framework编写一个无参数的构造函数 [英] Why must I have a parameterless constructor for Code First / Entity Framework

查看:94
本文介绍了为什么我必须为Code First / Entity Framework编写一个无参数的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是更多的问题我们为什么做事情,因为我的实际问题已经解决,但我不知道为什么。

This is more of a question of "Why we do things" as my actual problem was solved but I don't know why.

我正在处理以下代码在我的CountyRepository中:

I was dealing with the following code inside my CountyRepository:

public IEnumerable<County> GetCounties(string stateAbbr)
    {
        using (var db = new AppDbContext())
        {
            State state = (from s in db.States
                         where s.Abbr == stateAbbr
                         select s).First();

            return context.Counties.Where(c => c.StateID == state.StateID).ToList();
        }
    }

我上面创建的AppDbContext将转到自定义初始化程序:

The AppDbContext I created above would go to a custom Initializer:

  public class AppDbContextInitializer : DropCreateDatabaseIfModelChanges<AppDbContext> 
{
    protected override void Seed(AppDbContext context)
    {
        StatesList states = new StatesList();
        context.States.AddRange(states);
        context.Counties.AddRange(new CountiesList(states));

        context.SaveChanges();
    }
}

问题是,当我执行代码AppDbContext将在初始化程序中正确加载State和County信息,但是当它返回到County Repository时,AppDbContext为空,并且将由于State没有无参数构造函数而出错。我不希望我的State对象有一个无参数的构造函数,所以我一整天都看到一个解决方案,为什么AppDbContext将在县存储库中加载。我终于找到了以下解决方案:

The problem was, when I executed the code the AppDbContext would load the State and County information correctly in the Initializer, but when it came back into the County Repository, the AppDbContext was empty and would error due to "State has no parameterless constructor". I didn't want my State object to have a parameterless constructor so I looked all day for a solution to why the AppDbContext woulding load in the County Repository. I finally found the following solution:

加载相关对象时的异常。实体框架

这是一个简单的解决方案。添加无参数的构造函数并将其标记为已过时。我做到了,它的工作完美。

It was a simple solution. Add the parameterless constructor and mark it Obsolete. I did this and it worked perfectly.

我的问题是,为什么我要这样做?我通过使用自定义初始化程序的CodeFirst的多个示例,并没有提到需要一个空构造函数或标记它已经过时了。

My question is, WHY must I do this? I went through multiple examples of CodeFirst using custom Initializer and none of them mentioned requiring an empty constructor or marking it Obsolete.

有没有更好的解决方案或至少一个解释,所以我可以前进知识而不是混乱?

Is there a better solution or at least an explanation so I can go forward with knowledge instead of confusion?

推荐答案

必须有一个无参数的构造函数,但它可以是内部的或私有的。 ref question 3

There must be a parameterless constructor, but it can be internal or private. ref question 3

这篇关于为什么我必须为Code First / Entity Framework编写一个无参数的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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