Can I use New() method in Entity Framework partial classes - entity-framework

I have extended Entity Framework autogenerated classes with custom partial classes and added several new properties and business login into it. I need to populate those properties any time objects are either materialized from the database or created from scratch without a database contact.
Can I use or is it advised to use the New() method inside the class for that? (I know there is an event ObjectContext.ObjectMaterialized as well).
As an example, in my partial class i have a property
Public Property Employees As List(Of Employee)
and I want to instantiate that list somewhere (where?).

You could just write a default constructor for those entities where you set default property values. Notice Entity Framework doesn't create constructors for you, so they can easily be added in partial classes.

Related

Created a BasePOCO (which basically is similar to Entity Frameworks Database First EntityObject class)

At work, there is an application was developed using Entity Framework Database First approach. Therefore, our business entity classes are derived from Entity Framework Database First's EntityObject class.
Our team was to modify the application by moving from Entity Framework Database First approach to Entity Framework Code First approach.
However, we have to modify all out business entity classes that derive by modifying them in such a way that they Stop inheriting from the EntityObject class.
The problem is that we use a lot of EntityObject class's methods and other features in a lot of classes.
We were planning to create a BasePOCO class that will replace the Entity Frameworks Database First EntityObject class.
We would have to implement some methods in the BasePOCO class that would function in the same manner as some methods in the EntityObject class.
For example, we have the following line in a code file ( entity instance in the line of code below being of type EntityObject )
entity.GetType().GetProperty(firstFilter + _referenceKey);
we can replace it with (we have to implement methods that do something similar):
basePOCOEntityObject.GetType().GetProperty(firstFilter + _referenceKey);
I'm assuming there were probably many companies who moved from Entity Framework Database First approach to the Code First approach
Therefore, Has anyone already created something like out BasePOCO (which basically has a lot of functionalities that is similar to Entity Frameworks Database First EntityObject class)?
GetType() is not an EntityObject method. It's available on all objects.
EntityObject's methods mostly are replaced by methods on the DbContext.ChangeTracker. The main difference is that you have to have a DbContext object to call these methods. This can require some code restructuring.

Entity object for newly added objects instead of dynamic proxy Entity framework

i have a repository which have add and search methods
public virtual void Add(T obj)
{
_table.Attach(obj);
_table.Add(obj);
}
public virtual IEnumerable<T> Search(Expression<Func<T, bool>> predicate)
{
return _db.Set<T>().Where(predicate);
}
then on my controller after i add a new object of customer note using add method and save changes i use search to retrieve the notes based on customer Id and i get a list as the picture below and the newly added object is type poco class and all virtual navigation properties are not loaded i made a workaround by using include, is there explanation why EF do this
Quick watch List for retrieved list from search method
EF create proxies only for entity instances it creates - either implicitly when materializing a query or explicitly when you use DbSet.Create methods. Any method which receives user provided object instance (like Add, Remove, Attach, Entry etc.) does not modify (wrap with proxy) the passed object.
Why? Because doing so will make many methods throwing "The instance of entity type X cannot be tracked because another instance of this type with the same key is already being tracked" due to the fact that EF uses reference equality for tracking entity instances.
If you attach, add etc. plain (non proxied) object instances, they'll remain this way for the lifetime of the context or until explicitly detached.

EF Code First - Models , when should properties be instantiated in constructor?

I was wondering if there is a good explanation somewhere as to when a Property will need to be instantiated
in a model class constructor and when it is not necessary?
Docu on the MS EF site is good and covers a lot of related topics
Relationships and Navigation Properties - http://msdn.microsoft.com/en-us/data/jj713564
Configuring relationships with API http://msdn.microsoft.com/en-us/data/jj591620%20%22Configuring%20relationships%20with%20API
Entity Framework class library http://msdn.microsoft.com/en-us/library/hh289362%28v=vs.103%29.aspx
and im also part way through reading the Book Programming Entity Framework - Code First By Julia Lerman
I would like to better understand when a property needs to be instantiated in the Model constructor.
I see Samples in MS documentation and in the Book with and without newed up properties in the Model constructor.
There is most likely a good reason why some solutions use a constructor with newed Up objects and others not.
Seems like Virtual ICollection has the new List<> and complex type has new RefObj.
But simple virtual navigation property of type ModelObject are Ok without new.
Can I stick to a pattern without knowing the internals of each convention class. Or is there another topic I should be reading?
You never need to instantiate a property in the models constructor for EF to work, but it make it more convenient.
For example, If you had a class Order and it has children of Order Detail, and you wanted to add a new Order to your database.
Without initializing OrderDetails
var order = new Order();
order.OrderDetails.Add(new OrderDetail()); // this would error because OrderDetails is null
One option could be to call order.OrderDetails = new List();
before you use Add(), but then you would need to have that code repeated everywhere you wanted to use Add(). Instead you can put that code in the constructor, and then OrderDetails will be ready to use with all newly created Orders.

How can I use AutoMapper to map from DTOs to Entity Framework proxy classes?

I have a REST-style web application that uses EF code first. I'm using AutoMapper to map my classes to DTO classes for passing across the wire, and (hopefully) back.
When I map from my POCO classes to DTOs, I'm actually starting with an EF proxy object, since the objects I'm dealing with were the result of executing some sort of query against my DataContext. This seems to work fine, however.
When I get back a DTO class as part of a POST request, I can use AutoMapper to map it onto my POCO class, and this works fine too.
However because AutoMapper is just new()-ing the POCO objects rather than using the Create method on the EntitySet, I now have a POCO class rather than the corresponding EF proxy class. This makes it harder for me to add the data to my database etc.
How can I persuade AutoMapper to use EntitySet.Create? Or is there another way to achieve the same result?
Map.CreateMap creates an IMappingExpression object which has a method ConstructUsing that accepts a function that can be used as factory method for new objects. The mapped properties are used to set values. (This can be overriden by ConvertUsing, by the way).
For details, see Automapper - how to map to constructor parameters instead of property setters, AutoMapper using the wrong constructor, or How to use Automapper to construct object without default constructor.
In your case this could be something like:
Mapper.CreateMap<TDto, TPoco>()
.ConstructUsing((Func<TDto, TPoco>) (c => context.CreateObject<TPoco>()))
May be you can do like this,
First create the required object and then use that instance to map the DTO object,
var poco=EntitySet.Create()
Mapper.Map<DTOtype, POCOtype>(dto, poco);
Suppose you are accepting POCO object in your post method instead of DTO like
[HttpPost]
public ActionResult Save(Student std)
{
//do the stuff
}
suppose that Student is EF proxy class but when its bound to the form values using Modelbinder, it creates the new objects not the ones associated with data context. So first thing is, there is no difference if you accept DTO's in post and then convert them to proxy classes or you accept proxy classes in the first place.
Second thing is that if object already exist in database and you have just created it using automapper, you can associate with datacontext using attach method. and if its new object you will need to call the Add method to save it in the database.

Entity Framework 4.1 set EntityState on derived class throws Exception

I am facing a problem with EF 4.1. I am trying to Add a detached object to the DbContext. Problem is it is not the emd mapped object, but derived from it. Changing the mapping is not an option as some teams are using the model with the regular mapped BL-classes, but my project created a derived model for UI stuff. Even with casting I always receive a
InvalidOperationException ("Mapping and metadata information could not be found for EntityType ...").
What I want is EF to treat this as the base class and put the object into the DbSet of the BaseClass. The current EF code is:
Context.Entry(object).State = EntityState.Added
But I am open for other suggestions, even
via IObjectContextAdapter, as long as it can save the Base and the Supertype. This should be simple, right?! Mapping to a new Base-class instance is not good idea as the main objects temporary Id would not be updated after saving...
Thanks!
As I know this is not possible. You cannot use derived class from the entity instead of the entity. You must either map derived class as well or create new instance of the entity for persistence and copy all fields from your derived class instance to the entity instance.