Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
643 views
in Technique[技术] by (71.8m points)

c# - Why must I have a parameterless constructor for 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.

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();
        }
    }

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();
    }
}

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:

Exception when loading related objects. Entity Framework

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...