Reputation: 2355
I've created POCO classes with T4 Templates for EF 4.0 and generated mock for Context. Everything was great, but i don't like to initialize even small Mock-DB in C# code, so i've created some functions which generates Mock-DB from real DB and i wanted to serialize this object and use it later in some Unit Tests...
XML serialization fails, so i've tried binary serialization and serialization succeed, but deserialization failed.
Deserializer cannot find assembly "EntityFrameworkDynamicProxies-". How can i deserialize such thing (DynamicProxy?)...
Upvotes: 2
Views: 3426
Reputation: 842
I was successful able to solve this by registering a custom SerializationBinder with the BinaryFormatter: (EF6)
string file = "data.bin";
using (var ctx = new DataContext())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Binder = new MyBinder();
Entity e;
using (var s = File.OpenRead(file))
e = (Entity)bf.Deserialize(s);
ctx.Entities.Add(e);
ctx.SaveChanges();
File.Move(file, Path.Combine(archiveFolder, Path.GetFileName(file)));
}
class MyBinder : SerializationBinder
{
Dictionary<string, Type> types;
public MyBinder()
{
types = typeof(Entity).Assembly.GetTypes().Where(t => t.Namespace == "Foo.Model").ToDictionary(t => t.Name, t => t);
}
public override Type BindToType(string assemblyName, string typeName)
{
if (assemblyName.Contains("EntityFrameworkDynamicProxies-Foo"))
{
var type = typeName.Split('.').Last().Split('_').First();
return types[type];
}
var returnType = Type.GetType(String.Format("{0}, {1}", typeName, assemblyName));
return returnType;
}
}
Upvotes: 1
Reputation: 30152
If you create your instance of the class first from the entity context in the app the deserializes it, it may work for you. So in your application that is to deserialize this, attempt to do something like
context.YourSerializedObjectType.CreateObject(); where context is an instance of your entity object context.
I had a similar issue I was able to work around (partly) by doing this in an mvc web app's Application_Start
http://completedevelopment.blogspot.com/2010/09/aspnetmvcentity-framework-error-unable.html
give it a whirl.
Upvotes: 1
Reputation: 1063774
Dynamic proxies only exist on-demand, so are poor choices for serialisation. What us the error with XML? Ultimately I expect your best option here is to use a DTO layer, but that might also serialize with some other serializers. For example have you tried DataConttactSerializer, which may be able to cope? I've been adding proxy support to my own serializer but I haven't tried with ef4 yet.
Upvotes: 1