Implementing Generic Find<T> Method - c#

I'm implementing generics for Add, Remove, and Find, because I'm implementing multi-tenancy that gives me access to IQueryables from the database, as opposed to DbSets.
How Add was implemented:
Code before:
interest = db.Interests.Add(new Interest()) // Interests is dbSet
Code after:
interest = db.Add(new Interest()) // Interests is dbSet
// in db class
public T Add<T>(T item) where T : class, ITenantData
{
var set = _appContext.Set<T>();
return set.Add(item);
}
This works. Now I'm trying to do the same thing for Find, but because I'm working with an Id and not a Typed parameter, I'm a bit stuck.
Code before:
var aptitude = db.Aptitudes.Find(interest.AptitudeId); // Aptitudes is a DbSet
Code after:
var aptitude = db.Find(interest.AptitudeId); // how to identify type?
I can't do this:
var aptitude = db.Aptitudes.Find(interest.AptitudeId);
Because Aptitudes is now an IQueryable.
So this is currently failing:
public T Find<T>(T query) where T : class, ITenantData
{
var set = _mentorContext.Set<T>();
return set.Find(query);
}
Because the type isn't identified - I get :
The type 'int' must be a reference type in order to use it as
parameter 'T' in the generic type or method
'App.Context.TenantContext.Find(T)' Service.cs
I'm a bit new to generics, any help here would be much appreciated.

Solve this with extension methods.
public IQueryable<T> Query<T>() where T : class, ITenantData
{
return _mentorContext.Set<T>().AsNoTracking();
}
...meanwhile in another class...
public static MentorContextExtensions
{
public static InterestEntity ByAptitudeId(
this IQueryable<InterestEntity> queryable,
int aptitudeId)
{
return queryable.SingleOrDefault(x => x.AptitudeId == aptitudeId);
}
}
...usage against IQueryable<T>...
db.Query<InterestEntity>().ByAptitudeId(interest.AptitudeId);
The example above returns a SingleOrDefault, but you could just as easily return sets (pre-filtered IQueryables or IEnumerables) using .Where, bools using .Any, etc.
To maintain usage of the .Find (by primary key) method on the IDbSet, you can do this:
public T Find<T>(params object[] keyComponents) where T : class, ITenantData
{
return _mentorContext.Set<T>().Find(keyComponents);
}
...and use it like this...
var aptitude = db.Find<Aptitude>(interest.AptitudeId);
... that said, using .Find may only be faster when you are doing inserts, updates, deletes with the entity, in some kind of mutation code. .Find will always keep the entity attached to the context, which is what you want when you need to mutate the data. However you cannot invoke .AsNoTracking() on it because it returns a single entity. If you only need the entity to read its properties or for display purposes, .AsNoTracking will keep the entire entity graph (the entity and its navigation / collection properties) detached from the context, which may be faster than using .Find. If you later want to use the same entity instance in mutation code, you can attach it to the context at that time.

Related

How do I get the first element of a dynamic/generic type

Is there any way to pass in a generic entity object and get the first in its query.
My intention is to call FirstOrDefault() on every table, and try catch for errors in the databases integrity.
It would have been nicer to be able to call it by string parameter e.g. db.Entity("myTable").FirstOrDefault() but such a method doesn't seem to exist.
Below is some generic T attempt, but i get the object not set to instance error.
// Called with
//GetFirstObject<myTable>(db.myTable);
public static void GetFirstObject<T>(object obj)
{
MethodInfo method = typeof(IEnumerable<T>).GetMethod("FirstOrDefault");
MethodInfo generic = method.MakeGenericMethod();
generic.Invoke(obj, null);
}
Why not use Set<T>()?
public T GetFirstObject<T>()
where T : class
{
return context.Set<T>().FirstOrDefault();
}
You can also pass filter expression:
public T GetFirstObject<T>(Expression<Func<T, bool>> filterExpression)
where T : class
{
return context.Set<T>().FirstOrDefault(filterExpression);
}
Assuming TEntity is the class representing your domain entity, you can try the following:
// Called with
// GetFirstObject<myTable>(db);
public static TEntity GetFirstObject<TEntity>(DbContext context) where TEntity : class
{
return context.Set<TEntity>().FirstOrDefault();
}
context.Set<TEntity>() will return the collection that represents the database table for TEntity. From there you can use any normal IQueryable extensions defined by LINQ (in this case, FirstOrDefault).
Perhaps it's just a working example, but worth pointing out that defining this kind of logic in static helper methods is normally not advisable. I'd suggest researching the 'Generic Repository Pattern' if you want to go down this route, which will be much more maintainable.

Cast object list to model

I am trying to create a generic method to get a list of records from different tables. Based on my internet research I thought this would work but have been unable to make it work. A lot of code is omitted for clarity:
The method:
public IEnumerable<object> GetEntityUpdates(string entity)
{
string query = "select * from " + entity;
IEnumerable<object> entityList;
entityList = db.Database.SqlQuery<object>(query).ToList();
return entityList;
}
This is then the calling code where I am attempting the cast which fails no matter how I spin it:
var theList = da.GetEntityUpdates("EntityName");
IEnumerable<EntityName> entityList = theList.Cast<EntityName>();
EntityName is a database model which corresponds to the select above.
InvalidCastException is then thrown.
"Unable to cast object of type 'System.Object' to type 'EntityName'."
Change your GetEntityUpdates to use generics. Entity Framework also has a Set method for DbContext that lets you access entities of a certain type. More info here: https://msdn.microsoft.com/en-us/library/gg696521(v=vs.113).aspx
public IEnumerable<T> GetEntityUpdates<T>() where T : class
{
return db.Set<T>().ToList();
}
Then to call it you just pass in your entity class as a type parameter:
var foo = da.GetEntityUpdates<EntityName1>();
var bar = da.GetEntityUpdates<EntityName2>();
The method you're using to extract information, SqlQuery<object>, relies on reflection in order to build your objects, not sure what framework is being used but would guess making your method generic would solve the problem
public IEnumerable<T> GetEntityUpdates<T>(string entity)
{
string query = "select * from " + entity;
return db.Database.SqlQuery<T>(query).ToList();
}

How to cast value returned by Invoke to IEnumerable<type> where type is some variable of type T?

I have the situation, where I want to call some generic method on another object and get IEnumerable result.
private void SomeFunction(Type type)
{
var method = context.GetType()
.GetMethods()
.FirstOrDefault(_ => _.Name == "GetStorage" && _.IsGenericMethod);
var storage = getStorage.MakeGenericMethod(type)
.Invoke(context, new object[] {})
.AsEnumerable();
//Some magic needed here. Something like Cast<type>,
//but type - variable
//More code ...
}
Could anyone suggest me how to figure out this situation. Thank you.
I have already seen this and similar questions:
Casting Results from Generic Method Invocation?
But they doesn't answer on my question, how to do same, when I don't know type, to which I want to cast, and type is stored as variable.
I can't makeSomeFunction a generic method, because the real situation is that I am iterating some list with System.Type and calling lambda (i. e. SomeFunction) on each element
There are some things you need to do to get what you want. You say you want to have a lambda, but that means that you need to define that lambda, which is on a type you do not know yet. You can redesign your lambda into an interface.
Also, I find it much easier to define a generic class that does exactly what I want. By creating an instance of this class through reflection, and only there, I can implement the rest of the class in a strong typed way. This takes away the 'not knowing what type I have' in most places.
Like this. First, the executor interface:
public interface ISomeFunctionExecutor
{
void Execute(SomeContext context);
}
Then the interface that I need to implement on the entities, which is the lambda so to speak.
public interface IEntityWithSomeFunction
{
void SomeFunction();
}
Now the implementation of the executor.
public class SomeFunctionExecutor<TType> : ISomeFunctionExecutor
{
public void Execute(SomeContext context)
{
var data = context.GetStorage<TType>().Cast<IEntityWithSomeFunction>();
foreach (var item in data)
{
item.SomeFunction();
}
}
}
And finally, the usage of it all:
// Usage:
SomeContext context = new SomeContext();
Type type = typeof(SomeEntity);
var executorType = typeof(SomeFunctionExecutor<>).MakeGenericType(type);
var executor = Activator.CreateInstance(executorType) as ISomeFunctionExecutor;
if (executor != null)
{
executor.Execute(context);
}
Basically the point is: define a generic class to do what you need to do where you do know the type, and create an instance of this class using reflection. It makes it much easier than having a whole method where you do not know the type.

How to define generic extension method that returns type of sub generic

I have a definition like this:
public static IQueryable<D> ReturnDTO<E, D>(this IQueryable<E> query)
where D : BaseDTO, new()
where E : BaseObjectWithDTO<D, int>
{
//expression tree code to convert
}
BaseObjectWithDTO defines what type it's DTOs are. Hence I would have thought the by defining E I would have been also defining D.
But IQueryable.ReturnDTO() requires that the generic parameters be specified like this:
IQueryable.ReturnDTO<someEntity, someDTO>();
Which is obviously UGLY.
I tried making this IQueryable<E> as this IQueryable<BaseObjectWithDTO<D, int>> instead but then this has nothing as the in of the func because it won't take a type inferred by the Generic Parameter of the IQuerayble:
var projection = Expression.Lambda<Func<E, D>>(memberInitExpression, itemParam);
Ideas on how to get this to not require the types be passed every time?
Unfortunately, C#'s generic type inference system isn't as powerful as it could be. If you include a parameter involving D, then it can infer it. For example...
public static IQueryable<D> ReturnDTO<E, D>(this IQueryable<E> query,
IQueryable<BaseObjectWithDTO<D, int>> dummy)
// now you can do...
myQueryable.ReturnDTO(myQueryable);
// instead of
myQueryable.ReturnDTO<BaseObjectWithDTO<BaseDTO, int>, BaseDTO>();
It's confusing and arguably a poor design to pass the same variable in twice, but it's better (IMHO) than having to explicitly specify the types or resort to reflection or other runtime techniques to extract the types (when that's otherwise unnecessary).
Since you aren't actually going to use the dummy parameter, it doesn't matter what the value is, as long as the type is right, so you might still be able to use this at the end of a query chain, e.g. this will still return the expected value, even though you pass in two different IQueryables.
var result = otherQueryable.Where(...).ReturnDTO(otherQueryable);
If you prefer to be slightly less cryptic, you could make the dummy parameter D dummy, and then e.g. myQueryable.ReturnDTO(default(SomeDTO)) (here using default as a clear way of getting a null or default value without having a reference to a variable/field/property of that type) if you prefer.
I don't think it is possible as you currently have it designed, this MSDN page states that type inference is not possible in this scenario:
The same rules for type inference apply to static methods and instance
methods. The compiler can infer the type parameters based on the
method arguments you pass in; it cannot infer the type parameters only
from a constraint or return value.
That means you have to pass in a parameter of your type to this method for the compiler to be able to infer the types.
You have to specify the type, but it doesn't have to be done explicitly in the q.Return<E,D>(). There are ways that you can pass specify the type parameter so that it can be inferred implicitly. To do that, you'll need to change the signature a bit.
public static IQueryable<D> ReturnDTO<E, D>(this IQueryable<E> query, D dtoTypeExample = default(D))
where D : BaseDTO, new()
where E : BaseObjectWithDTO<D, int>
{
//expression tree code to convert
}
Now, even though there's a default parameter, the compiler won't be able to get it unless you pass some argument in. The thing you pass in doesn't have to be used by the method in any other way though. For example, assume you have:
public class ProductDTO : BaseDTO {
public static ProductDTO Empty { get { return new ProductDTO(); } }
}
public class Product : BaseObjectWithDTO<ProductDTO,int> {
public static IQueryable<Product> QuerySource { get; set; }
}
You could then call:
ProductDTO dto = Product.QuerySource.ReturnDTO(ProductDTO.Empty);
I'm not saying that this is necessarily a good idea, but you could do it. Also, it doesn't have to be the actual type that you pass in - you just need to pass in something that's close enough for the compiler to infer the intended type. For example, you could have a signature like:
public static IQueryable<D> ReturnDTO<E, D>(this IQueryable<E> query, Func<D,D> dtoIdentity = default(Func<D,D>))
where D : BaseDTO, new()
where E : BaseObjectWithDTO<D, int>
{
//expression tree code to convert
}
then if you have:
public class ProductDTO : BaseDTO {
public static ProductDTO Identity(ProductDTO dto){ return dto; };
}
public class Product : BaseObjectWithDTO<ProductDTO,int> {
public static IQueryable<Product> QuerySource { get; set; }
}
You could then call:
ProductDTO dto = Product.QuerySource.ReturnDTO(ProductDTO.Identity);
This might make more semantic sense to some, but it's somewhat subjective. Once again, I'm not recommending this, just saying that you can do it. If you do decide to do it though, it might save you a little work to have a self-referential generic base (Warning: Eric Lippert discourages this kind of thing). But anyway, your design would then look like:
public abstract class BaseDTO<T> where T : BaseDTO<T>, new()
{
public static T Empty { get { return new T(); } }
}
public class ProductDTO : BaseDTO<ProductDTO> { }
You could also add the type constraint to your ReturnDTO method if you want to enforce an invariant that all DTOs were then self-referential derivatives of BaseDTO<T> with public parameterless constructors. But, if you're trying to write what would conventionally be considered good code you probably won't do any of this and you'll just close your eyes and explicitly use the parameter constraint if you think it's ugly.
There is one other thing I thought of, which wouldn't be so frowned upon. Think about the Queryable.Cast<T> and Queryable.OfType<T> methods. They take a non generic IQueryable parameter but returns an IQueryable<T>. If you make sure to validate your assumptions about the parameter, it's probably clean enough. Then you would lose some compile-time type-safety though. You would need to have a non-generic base like BaseObjectWithDTO that BaseObjectWithDTO<TData,TKey> would inherit from. Your method would then look like:
public static IQueryable<D> ReturnDTO<D>(this IQueryable<BaseObjectWithDTO> query)
where D : BaseDTO, new()
{
if(query == null) throw new ArgumentNullException("query");
if( !typeof(BaseObjectWithDTO<D,int>) .IsAssignableFrom(query.GetType().GetGenericParameters()[0]))
throw new ArgumentOutOfRangeException("query");
//expression tree code to convert
}
That's not terrible. But it might not be good either. It's probably better than the other options I listed, but who knows.
Another syntax that might work for you just occurred to me, but it's also pretty abusive. Imagine you did go the BaseDTO<T> where T : BaseDTO<T>,new() route. You could declare the method on that type to extract the DTO queryable. This is what I'm thinking:
public abstract class BaseDTO<T>
where T : BaseDTO<T>, new()
{
public static T From(BaseObjectWithDTO<T,int> entity){
if(entity == null) throw new ArgumentNullException("entity");
//expression tree code to convert
}
}
then you don't really need that method ReturnDTO as an extension method anymore, because you have normal LINQ. You could still add it as syntactic sugar if you want, but using these semantics instead, your call ends up looking like:
IQueryable<ProductDTO> dtoQuery = from entity in Product.QuerySource select ProductDTO.From(entity);
which can also be written as
Product.QuerySource.Select(entity => ProductDTO.From(entity));
and if you were using an IEnumerable instead of an IQueryable could be
Product.QuerySource.Select(ProductDTO.From);
Please remember: All I'm saying is that you can do things this way. I'm not saying you should.

EF4 Cast DynamicProxies to underlying object

I'm using Entity Framework 4 with POCO template.
I have a List where MyObject are dynamic proxies. I want to use the XmlSerializer to serialize this list, but I don't want them serialized as DynamicProxies but as the underlaying POCO object.
I know about ContextOptions.ProxyCreationEnabled, but I do not want to use that. I just want to know how to cast a proxy object to it's underlaying POCO to serialize.
Faced the same issue today and used Value Injecter to solve it. It's as simple as:
var dynamicProxyMember = _repository.FindOne<Member>(m=>m.Id = 1);
var member = new Member().InjectFrom(dynamicProxyMember) as Member;
Ill dig these old bones up by offering a solution that helped me. Hopefully, it will help someone that reads it.
So, there are actually two solutions. If you don't want lazy loading you can always turn off dynamic proxies and that will give you just the entitiy:
public class MyContext : DbContext
{
public MyContext()
{
this.Configuration.ProxyCreationEnabled = false
}
public DbSet<NiceCat> NiceCats {get; set;}
public DbSet<CrazyCat> CrazyCats {get; set;}
public DbSet<MeanCat> MeanCats {get; set;}
}
The other solution is to use the ObjectContext to get the original entity type the proxy stands in for:
using (var db = new MyContext())
{
var meanAssCat = context.MeanCats.Find(CurrentCat.Id)
var entityType = ObjectContext.GetObjectType(meanAssCat.GetType());
}
As you don't want to turn ProxyCreation off, you are stuck DynamicProxy objects wherever you put virtual keyword for object property (EF Context inherits your object and replaces virtual properties with DynamicProxy objects). These DynamicProxy objects do not inherit from your POCO entities, they just have same properties and can be used instead of your POCO. If you really must to convert to POCO object (and I don't believe that someone will come up with a way to cast it), you may try to workaround by writing copy constructor which will copy all properties from passed argument (not very smart from performance standpoint, but what you have to do, you have to do), or maybe using System.Xml.Serialization.XmlTypeAttribute in parent object which contains your dynamic proxy instead of poco to tell serializer how to serialize virtual property (into which type).
Disclaimer: I've created a somewhat generic solution to this problem. I found this old question while searching for a solution so I figured I'd share my solution here to help whoever may be stubbing his or her toe on the same problem.
I ran into the same problem: I needed to get some stuff from Entity Framework, and then use ASP.NET Web Api to serialize it to XML. I've tried disabling lazy loading and proxy creation and using Include(), but on anything but the most basic class hierarchy that led to gigantic SQL queries that took several minutes to execute. I found that using lazy loading and referencing each property recursively was many, many times faster than loading the tree all at once, so I figured I'd need a way to lazy load everything, get it in the form of a POCO, and then serialize it.
I've used this answer by Gert Arnold as the basis for this solution, and then worked from there.
I've created an Unproxy method in the DBContext that takes a (proxied) class instance (something you'd get back from DbContext.Find(id) for instance) and returns that entity as an actual POCO type, with each property, sub-property etc. fully loaded and ready for serialization.
The Unproxy method and some readonly fields:
readonly Type ignoreOnUnproxyAttributeType = typeof(IgnoreOnUnproxyAttribute);
readonly string genericCollectionTypeName = typeof(ICollection<>).Name;
public T UnProxy<T>(T proxyObject) where T : class
{
// Remember the proxyCreationEnabled value
var proxyCreationEnabled = Configuration.ProxyCreationEnabled;
try
{
Configuration.ProxyCreationEnabled = false;
T poco = Entry(proxyObject).CurrentValues.ToObject() as T; // Convert the proxy object to a POCO object. This only populates scalar values and such, so we have to load other properties separately.
// Iterate through all properties in the POCO type
foreach (var property in poco.GetType().GetProperties())
{
// To prevent cycles, like when a child instance refers to its parent and the parent refers to its child, we'll ignore any properties decorated with a custom IgnoreOnUnproxyAttribute.
if (Attribute.IsDefined(property, ignoreOnUnproxyAttributeType))
{
property.SetValue(poco, null);
continue;
}
dynamic proxyPropertyValue = property.GetValue(proxyObject); // Get the property's value from the proxy object
if (proxyPropertyValue != null)
{
// If the property is a collection, get each item in the collection and set the value of the property to a new collection containing those items.
if (property.PropertyType.IsGenericType && property.PropertyType.Name == genericCollectionTypeName)
{
SetCollectionPropertyOnPoco<T>(poco, property, proxyPropertyValue);
}
else
{
// If the property is not a collection, just set the value of the POCO object to the unproxied (if necessary) value of the proxy object's property.
if (proxyPropertyValue != null)
{
// If the type of the property is one of the types in your model, the value needs to be unproxied first. Otherwise, just set the value as is.
var unproxiedValue = (ModelTypeNames.Contains(property.PropertyType.Name)) ? SafeUnproxy(proxyPropertyValue) : proxyPropertyValue;
property.SetValue(poco, unproxiedValue);
}
}
}
}
return poco; // Return the unproxied object
}
finally
{
// Zet ProxyCreationEnabled weer terug naar de oorspronkelijke waarde.
Configuration.ProxyCreationEnabled = proxyCreationEnabled;
}
}
ModelTypeNames is a property I've added to my DBContext that simply returns all the types used in the model. That way we'll know which types we need to unproxy:
private Collection<string> modelTypeNames;
private Collection<string> ModelTypeNames
{
get
{
if (modelTypeNames == null)
{
// We'll figure out all the EF model types by simply returning all the type arguments of every DbSet<> property in the dbContext.
modelTypeNames = new Collection<string>(typeof(VerhaalLokaalDbContext).GetProperties().Where(d => d.PropertyType.Name == typeof(DbSet<>).Name).SelectMany(d => d.PropertyType.GenericTypeArguments).Select(t => t.Name).ToList());
}
return modelTypeNames;
}
}
To deal with ICollection<> properties, we need to first instantiate a new generic collection (I'm using reflection to create a HashSet<> with the right type argument), iterate through all the values, unproxy each value and add it to the new HashSet, which is then used as the value for the POCO's property.
private void SetCollectionPropertyOnPoco<T>(T poco, PropertyInfo property, dynamic proxyPropertyValue) where T : class
{
// Create a HashSet<> with the correct type
var genericTypeArguments = ((System.Type)(proxyPropertyValue.GetType())).GenericTypeArguments;
var hashSetType = typeof(System.Collections.Generic.HashSet<>).MakeGenericType(genericTypeArguments);
var hashSet = Activator.CreateInstance(hashSetType);
// Iterate through each item in the collection, unproxy it, and add it to the hashset.
foreach (var item in proxyPropertyValue)
{
object unproxiedValue = SafeUnproxy(item);
hashSetType.GetMethod("Add").Invoke(hashSet, new[] { unproxiedValue }); // Add the unproxied value to the new hashset
}
property.SetValue(poco, hashSet); // Set the new hashset as the poco property value.
}
Note that I'm calling SafeUnproxy rather than Unproxy. This is because of a weird issue with type inference. Usually when you pass a proxy object to Unproxy(), type inference will infer that T is the POCO type you actually want, not the type of the dataproxy (the one that looks like YourModelPocoType_D0339E043A5559D04303M3033 etc). However, occasionally it does infer T as the dataproxy type, which blows up the
T poco = Entry(proxyObject).CurrentValues.ToObject() as T;
line, because the poco object can't be cast to the proxy type, causing the as operator to return null. To fix this, SafeUnproxy calls the Unproxy method with an explicit type parameter rather than relying on inference: it checks the type of the parameter you pass it, and if the namespace is System.Data.Entity.DynamicProxies, it'll use the type's BaseType (which in the case of a dynamicproxy type is the corresponding POCO type) as the generic type argument.
private object SafeUnproxy(dynamic item)
{
// ProxyCreation is off, so any reference or collection properties may not yet be loaded. We need to make sure we explicitly load each property from the db first.
ExplicitlyLoadMembers(item);
// Figure out the right type to use as the explicit generic type argument
var itemType = item.GetType();
Type requiredPocoType = (itemType.Namespace == "System.Data.Entity.DynamicProxies") ?
itemType.BaseType :
itemType;
// Call Unproxy using an explicit generic type argument
var unproxiedValue = typeof(VerhaalLokaalDbContext).GetMethod("UnProxy").MakeGenericMethod(requiredPocoType).Invoke(this, new[] { item });
return unproxiedValue;
}
Making sure each property is loaded from the database is a matter of iterating through the properties of the object and checking IsLoaded:
private void ExplicitlyLoadMembers(dynamic item)
{
foreach (var property in ((Type)item.GetType()).GetProperties())
{
DbEntityEntry dbEntityEntry = Entry(item);
var dbMemberEntry = dbEntityEntry.Member(property.Name);
// If we're dealing with a Reference or Collection entity, explicitly load the properties if necessary.
if (dbMemberEntry is DbReferenceEntry)
{
if (!dbEntityEntry.Reference(property.Name).IsLoaded)
{
dbEntityEntry.Reference(property.Name).Load();
}
}
else if (dbMemberEntry is DbCollectionEntry)
{
if (!dbEntityEntry.Collection(property.Name).IsLoaded)
{
dbEntityEntry.Collection(property.Name).Load();
}
}
}
}
Finally, the IgnoreOnUnproxyAttribute used to avoid cycles:
[System.AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
sealed class IgnoreOnUnproxyAttribute : Attribute
{
}
Usage is as follows:
MyDbContext db = new MyDbContext();
public Story Get(int storyId)
{
var lazyStory = db.Stories.SingleOrDefault(s => s.Id == storyId);
var unproxied = db.UnProxy(lazyStory);
return unproxied;
}
Performance isn't spectacular due to all the reflection going on, but execution time is on average only slightly (i.e. less than a second) longer than when lazy loading an entity, iterating through all its properties, and then serializing the dynamicproxy itself. Also, it's much, much faster than when using Include() which is dreadfully slow and error-prone.
Hope it helps somebody.
I faced with the same issue in EF 5. I was trying to serialize my entity objects to XML. #Koreyam s answer gave me a hint. I developed it little bit more.
Somewhere in my code i was calling the serializer like this
string objXML = EntitySerializer.Serialize(entity);
Serialize method is generic. So method header is like this :
public static string Serialize<T>(T tObj) where T : class, new()
So in my method body i use value injecter :
T obj = new T().InjectFrom(tObj) as T;
it just solved my issue for all of my entitites.

Categories

Resources