C#Generic.ForEach不起作用?或EF简单的方法来排除属性

时间:2015-09-25 16:30:38

标签: c# entity-framework linq

我需要从List

清除一些属性

CategoryAccount是类

获取清单

List<CategoryAccount> ret = context.CategoryAccounts.ToList();

使用ForEach清除

//Clear Accounts poperty to null
//Accounts is List<Acccount>
ret.ForEach(x => x.Accounts = null);
//Clear Owner poperty to null
//Owner is class Owner 
ret.ForEach(x => x.Owner = null);

//In result
ret[0].Account != null
ret[0].Owner != null

或在context.CategoryAccounts中排除属性。

我不想使用Select(x => new { prop1 = x.prop1, prop2 = x.prop2? ///} - 必须包含模型中的太多属性。

1 个答案:

答案 0 :(得分:5)

You seem to be using lazy loading. You have to trigger load before assigning any values to navigation properties. You can do it using Include.

List<CategoryAccount> ret = context.CategoryAccounts
    .Include(x => x.Accounts)
    .Include(x => x.Owner)
    .ToList();
//Clear with ForEach

//Clear Accounts poperty to null
//Accounts is List<Acccount>
ret.ForEach(x => x.Accounts = null);
//Clear Owner poperty to null
//Owner is class Owner 
ret.ForEach(x => x.Owner = null);