Create an Entity Framework Entity at runtime by string - entity-framework

I'm not sure if there is a way to do this or if I should even be doing this at all. But I have a method that can be called on certain of my entities. But I want to write this method once to apply to all of the entities because I know they are similar in a certain way.
Is there a way to create an instance of an entity, at runtime, by referencing a string value of that entity type?
So my method would be GetSomething(Entity e)
and that can be called on 10 different entities.
at runtime I have a string "Entity4".
I want to create an instance of that entity and call the GetSomething() method on it.
Inside of GetSomething() I want to do:
using (var db = new TalonEF_test.GISTestProductionEntities())
{
List<runtimeEntity> es = db.runtimeEntity.Where(o => o.OB == oid).ToList();
}

"But I want to write this method once to apply to all of the entities because I know they are similar in a certain way."
Write an interface which defines this similarity and then have your entities implement it. When you need to refer to objects which could be any of the entities, use the interface. If you need to run concrete queries against EF, you can call GetType on your entity and use that in DbContext.Set<T> to get a DbSet reference to run queries against.

Related

Map to customized (dynamically generated but with same structure) tables entity framework core

I have dbcontext class let's say.
"tblProp".
On querying I want it to point to "tblProp_1" when I pass 1 as an argument.
Is this type of querying through ef core possible?
There is class method in dbcontext named entity.toTable("tblProp").
Is it possible to use that method to map to what I have described above?
Yes, you can do that provided that these databases share the same schema. You can create a parameterized constructor and pass the parameter whiling creating the DB context.
You can't do it without calling OnModelCreating method which is called once per DbContext type and have the caching functionality.
Following is possible through linq2db.EntityFrameworkCore
var items = context.DbSet<Table>().ToLinqToDBTable().TableName("table_3")
.Where(...)
.ToList();
For sure ChangeTracker will be not availaible but CRUD operation can be performed in other way:
var affected = context.DbSet<Table>().ToLinqToDBTable().TableName("table_3")
.Where(...)
.Set(v => v.Field, someValue)
.Update();
Source

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.

Linq to Entities without generic parameter

If this is a property implementation where Context is an Entity Framework DbContext and Tours is a DbSet...
public IQueryable ListQuery => Context.Tours;
... then the calling code has limited ability to continue the query. For example, I can't even call ToList() on the result.
How do I return an un-typed query, such that I can do things like Take and Skip on the result, without the calling code knowing what the type is?
I don't want the type to leak out of the interface, because then my data access code is tied to one EF model in particular.
I cast the result to IQueryable<object>. I'm not sure why that's allowable. Is it because its covariant?

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 - Get Object as Collection

Is it possible to get a collection (Dictionary) out of an Entity Object? I need this in order to pass parts of the Properties of the object to a function that needs an IDictionary.
Use:
Context.EntitySetName.AsEnumerable().ToDictionary(o => o.Key, o => o.Value);
Some detail on this:
ToDictionary is not supported in LINQ to Entities. This means that LINQ query string containing ToDictionary will compile, but will not execute, because the Entity Framework does not know how to translate them into SQL. Therefore, you have to execute the query on the database server first. So you have to project your set into a list first, which enumerates the entity set. AsEnumerable will do that. Obviously, if the entity set is large, you probably don't want to do this with the whole thing. Use a Where call or a LINQ query to reduce the result set to only the items you want in the dictionary first.
I don't think I fully understand your question. I don't know of any way of binding your database tables to IDictionary properties if that is what you are referring to, but you should be able to create whatever properties or methods you need to build a dictionary, and pass that. Is writing a business object method not an option for some reason?