1

I am upgrading one of existing projects DAL to Entity Framework. In leagcy DAL I hav consturctors like e.g.

public class User{
    public User(){}

   // This constructor loads data from database where UserID is found
   public User(int UserID){} 

}

So how can I implement this in EF i.e. When I pass UserID in parameterized constructor it should populate the User Entity from database ?

3 Answers 3

1

When I pass UserID in parameterized constructor it should populate the User Entity

Looks like turning to Entity Framework also requires a paradigm shift. You were used to Active Record or similar. When you work with EF an important notion is that entities (i.e. classes like User) are persistence ignorant.

The context is responsible for materializing entity objects from the database, tracking their changes and saving changes. The entities themselves are not involved in this.

So in your case you'd no longer get a User by

var user = new User(1);

but by

using(var context = new MyContext())
{
    var user = context.Users.Find(1);
    // in ObjectContext: context.Users.Single(u => u.UserId == 1)
}

It looks more elaborate this way, but now the User is a simple POCO (if you work code first). There's nothing inside of it that the legacy DAL must have had.

Sign up to request clarification or add additional context in comments.

Comments

0

research using the Repository abstraction pattern in EF. In fact if you have an existing DAL, also check out the Logical unit of work abstraction pattern examples for EF. You will most likely need it.

Comments

0

Entity Framework objects require a default constructor.

To get around this you can hook into the ObjectMaterialized event of the Context.

Context.BaseObjectContext.ObjectMaterialized += ObjectContext_OnObjectMaterialized;

private void ObjectContext_OnObjectMaterialized(
    object sender, 
    ObjectMaterializedEventArgs e)
{
    //e.Entity is the newly created object
    //you can cast it and call into it to do any initilisation etc.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.