我用以下解決方案來克隆我的實體,沒有章法,其中在實體上和我的表循環引用所需的有關數據屬性得到了保留。我甚至有實體互相指責對方沒有任何問題。 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並不意味着其他解決方案將無法正常工作。 –