我正在尝试通过WCF从Entity Framework检索对象列表,但收到以下异常:
尝试序列化参数http://tempuri.org/:GetAllResult时出错。数据协定名称为'TestObject_240F2B681A782799F3A0C3AFBE4A67A7E86083C3CC4A3939573C5410B408ECCE:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies‘的类型'System.Data.Entity.DynamicProxies.TestObject_240F2B681A782799F3A0C3AFBE4A67A7E86083C3CC4A3939573C5410B408ECCE’不应为InnerException消息。考虑使用DataContractResolver或将任何未知类型静态添加到已知类型列表中-例如,通过使用KnownTypeAttribute属性或通过将它们添加到传递给DataContractSerializer.‘的已知类型列表中。更多详情请查看InnerException。
我过去使用过WCF,但从未与实体框架一起使用过。我的所有实体都是通过实体框架生成的,并用DataContract和DataMember属性进行了注释。我的任何实体上都没有导航属性。
被调用的GetAll()方法位于抽象服务类中:
[ServiceContract]
public interface IService<T>
{
[OperationContract]
List<T> GetAll();
}
我使用ChannelFactory来调用我的实现:
Binding binding = new NetTcpBinding();
EndpointAddress endpointAddress = new EndpointAddress("net.tcp://localhost:8081/" + typeof(TestObjectService).Name);
using (ChannelFactory<ITestObjectService> channel = new ChannelFactory<ITestObjectService>(binding, endpointAddress))
{
ITestObjectService testObjectService = channel.CreateChannel();
testObjects = testObjectService.GetAll();
channel.Close();
}
我就是这样主持的:
Type type = typeof(TestObjectService);
ServiceHost host = new ServiceHost(type,
new Uri("http://localhost:8080/" + type.Name),
new Uri("net.tcp://localhost:8081/" + type.Name));
host.Open();
当使用调试时,它从数据库中查找对象,但是,它无法返回对象。
对于我可能会出错的地方有什么想法吗?
发布于 2010-07-30 23:49:32
要弄清楚这是一件很痛苦的事情,但这是因为EntityFramework创建了一个类的“代理”。我拥有的TestObject类设置正确,但它创建了一个名为: TestObject_240F2B681A782799F3A0C3AFBE4A67A7E86083C3CC4A3939573C5410B408ECCE的类
要使ChannelFactory + WCF +实体框架一起工作,您必须进入上下文构造函数并添加以下内容:
ContextOptions.ProxyCreationEnabled = false;
我希望这对其他人有帮助。
发布于 2012-02-28 00:21:07
当使用DbContext API for Code First (EF 4.3)时,我必须这样做:
public class MyClass : DbContext
{
public MyClass()
{
base.Configuration.ProxyCreationEnabled = false;
}
}
发布于 2015-01-25 08:43:41
对于EntityFramework 6.0,我还必须更改配置:
public class MyContext : DbContext
{
public MyContext() : base("name=MyContext")
{
Configuration.ProxyCreationEnabled = false;
}
}
https://stackoverflow.com/questions/3372895
复制相似问题