2017-03-31 50 views
0

要查找具有1:1關係的表,LinqPad會生成一個屬性,該屬性指向使用查找值的對象集合。如何禁用這個?如何禁用Linqpad中生成的導航屬性?

當我嘗試使用Newtonsoft.JSON序列化表時,會導致問題。

+0

你可能意指'n:1'關係。無論如何,Linqpad只是一個快速的數據訪問工具(以及更多)。我創建了一個LINQ到SQL的上下文,並且沒有什麼可配置的。我甚至認爲在項目代碼中使用上下文時是不可能的。 –

+0

'.Select(r => new {r.c1,r.c2,...})''? –

回答

2

您不能防止LINQPad從產生這些屬性,但你能告訴Newtonsoft不序列化他們,IContractResolver

http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size

寫您的合同解析器類的我的分機查詢,所以它將適用於所有查詢。在過濾屬性的CreateProperties方法中,您需要對屬性類型應用條件以排除導航屬性。下面將排除所有N:1和1:1屬性:

public class FlatResolver : DefaultContractResolver 
{ 
    public static JsonSerializerSettings Settings = 
    new JsonSerializerSettings { ContractResolver = new FlatResolver() }; 

    protected override IList<JsonProperty> CreateProperties (Type type, MemberSerialization memberSerialization) 
    { 
    IList<JsonProperty> properties = base.CreateProperties (type, memberSerialization); 

    properties = properties 
     .Where (p => !p.PropertyType.GetCustomAttributes (typeof (System.Data.Linq.Mapping.TableAttribute)).Any()) 
     .ToList(); 

    return properties; 
    } 
} 

然後序列化,只是這樣做:

JsonConvert.SerializeObject (myObject, FlatResolver.Settings).Dump(); 

您可以使用類似的邏輯,排除1:N,通過檢查爲一個實體類型的IEnumerable。