如何在EF 4中获得我的子类的IEnumerable结果。就像,我的基类的ObjectSet也是一个EntitySet ..但对于我的孩子,我无法查询它们.White一些尝试错误我成功读取,更新,创建,删除..但不查询(或列出)我的子类..
我这样读:
public Member GetMember(Guid id) { try { using (EntitiesContainer db = new EntitiesContainer()) { return db.Resources.SingleOrDefault(x => x.Id == id) as Member; } } catch (Exception ex) { Log entry = new Log(); entry.ClassName = GetType().Name; entry.Message = ex.Message; entry.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; entry.StackTrace = ex.StackTrace; _logger.Log(entry, SeverityEnum.Critical); } return new Member(); }
我这样创作:
public Member CreateMember(Member member, string userName) { try { using (EntitiesContainer db = new EntitiesContainer()) { member.Id = (Guid)_userService.GetUser(userName).ProviderUserKey; db.Resources.AddObject(member); db.SaveChanges(); } } catch (Exception ex) { Log entry = new Log(); entry.ClassName = GetType().Name; entry.Message = ex.Message; entry.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; entry.StackTrace = ex.StackTrace; _logger.Log(entry, SeverityEnum.Critical); } return member; }
我这样更新:
public Member UpdateMember(Member member) { try { using (EntitiesContainer db = new EntitiesContainer()) { db.Resources.Attach(GetMember(member.Id)); db.Resources.ApplyCurrentValues(member); db.SaveChanges(); } } catch (Exception ex) { Log entry = new Log(); entry.ClassName = GetType().Name; entry.Message = ex.Message; entry.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; entry.StackTrace = ex.StackTrace; _logger.Log(entry, SeverityEnum.Critical); } return member; }
等等......
但是对于列表或查询我的Members Collection或ObjectSet ......我无法做到这一点。
我尝试了类似的东西..但是它返回null或者施法异常。
public IEnumerable<Member> GetAll() { try { using (EntitiesContainer db = new EntitiesContainer()) { var test = db.Resources.ToList() as IList<Member>; // OR var test = db.Resources as IEnumerable<Member>; // OR var test = db.Resources.Cast<Member>(); // OR var test = db.Resources.AsEnumerable<Member>(); return test; } } catch (System.Exception ex) { Log entry = new Log(); entry.ClassName = GetType().Name; entry.Message = ex.Message; entry.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; entry.StackTrace = ex.StackTrace; _logger.Log(entry, SeverityEnum.Critical); } return null; }
我也尝试为我的会员创建一个ObjectSet,但是他们告诉我,我没有任何这个ObjectSet的EntitySet ..它的逻辑正确..
但是我在调试中看到我的会员有一个DynamicProxies的实例..这个属性是正确的,具有良好的价值..但我不知道如何达到它..我可以相信EF团队他们没有想一想......我在网上到处搜索..没有成功..我需要专家:)!
非常感谢你的时间!我很感激!
Cordialy, 朱利安。
答案 0 :(得分:1)
EntitiesContainer db = new EntitiesContainer();
var members = db.Resources.OfType<Member>();