我用以下解决方案来克隆我的实体,没有章法,其中在实体上和我的表循环引用所需的有关数据属性得到了保留。我甚至有实体互相指责对方没有任何问题。 serializaton所需的库是Json.Net(Newtonsoft.Json dll)。
private static T CloneObject<T>(T obj)
{
if (obj == null)
return obj;
string ser = JsonConvert.SerializeObject(obj, Formatting.Indented,
new JsonSerializerSettings() {
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
return (T) JsonConvert.DeserializeObject(ser, obj.GetType());
}
实例:
protected object CopyObj(Object obj)
{
return CloneObject(obj);
}
var cust1 = this.cts.Customers().Where(cc => cc.Id == 3).Include(cc => cc.Addresses).FirstOrDefault();
var cust2 = CopyObj(cust1) as Customers;
//Cust2 now includes copies of the customer record and its addresses
[序号实体框架对象转换JSON]的可能重复(http://stackoverflow.com/questions/657939/serialize-entity-framework-objects-into- json) –
@CraigStuntz不,因为我不想将属性maunally映射到一个新对象上。并问我如何使用JSON.NET完成 – Johan
建议的解决方案将适用于JSON.NET。如果你真的宁愿处理循环引用而不是赋值语句,那么这取决于你。但JSON.NET并不意味着其他解决方案将无法正常工作。 –