Dej*_*jan 9 entity-framework json.net
在我的设计中,我有一个类,它有一个属性,其类型可以继承自:
public class Feed
{
...
[JsonProperty(TypeNameHandling = TypeNameHandling.Auto)]
public FeedSource Source { get; set; }
...
}
public abstract class FeedSource { ... }
public class CsvSource : FeedSource { ... }
public class DbSource : FeedSource { ... }
Run Code Online (Sandbox Code Playgroud)
我正在使用Entity Framework将此对象加载并存储到数据库,我正在使用Json.NET将此对象序列化为JSON以进行进一步处理.
我偶然发现的问题是该$type属性包含EF代理的类型名称而不是"真实"类型名称.所以代替:
$type: "System.Data.Entity.DynamicProxies.CsvSource_0B3579D9BE67D7EE83EEBDDBFA269439AFC6E1122A59B4BB81EB1F0147C7EE12"
Run Code Online (Sandbox Code Playgroud)
这对其他客户来说毫无意义,我想得到:
$type: "MyNamespace.CsvSource"
Run Code Online (Sandbox Code Playgroud)
在我的JSON中.
实现这一目标的最佳方法是什么?
bam*_*bam 12
另一种不需要您更改EF配置的方法是使用自定义SerializationBinder,例如:
class EntityFrameworkSerializationBinder : SerializationBinder
{
public override void BindToName(Type serializedType, out string assemblyName, out string typeName)
{
assemblyName = null;
if (serializedType.Namespace == "System.Data.Entity.DynamicProxies")
typeName = serializedType.BaseType.FullName;
else
typeName = serializedType.FullName;
}
public override Type BindToType(string assemblyName, string typeName)
{
throw new NotImplementedException();
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
string json = JsonConvert.SerializeObject(entityFrameworkObject, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All, Binder = new EntityFrameworkSerializationBinder() });
Run Code Online (Sandbox Code Playgroud)
你可以做两件事:
通过设置ProxyCreationEnabled为 false 来禁用跟踪代理。您可以在上下文的Configuration属性中找到此属性。如果您对单个方法使用上下文GetXxx,则可以在不干扰其他上下文实例的情况下执行此操作。
AsNoTracking()恢复实体时使用扩展方法,如下所示:
MyContext.MyTable.AsNoTracking(). // rest of the query here
这表明您不需要实体的跟踪代理,因此您将获得实体类。这对上述配置没有干扰。
| 归档时间: |
|
| 查看次数: |
2845 次 |
| 最近记录: |