XVa*_*gas 5 linq asp.net-mvc inheritance entity-framework linq-to-sql
我正在尝试做类似于这篇文章的内容,我不会从特定实体中撤回所有列,但是我的框架使用了继承,并且在将其转换为匿名类型后,我失去了实体类型的范围.
我的Entity Framework的结构有一个名为Action的基本实体.从这里开始,我创建了两个名为Event和Activity的继承实体.我想撤回最后的X个动作并将它们传递给我的强类型视图,该视图接受一个Action,并从那里确定它是一个Activity还是Event并呈现正确的局部视图.
if(Model.GetType() == typeof(Event))
{
//render Event view
}
else if(Model.GetType() == typeof(Activity))
{
//render Activity view
}
Run Code Online (Sandbox Code Playgroud)
我可以将最后10个作为匿名类型拉出然后进行转换:
var result = from a in new DataContext().Actions
where a.UserId == someGuidValue
select new { a.CreatedOn, a.Summary };
List<Action> list = result.AsEnumerable()
.Select(o => new Action {
CreatedOn = o.CreatedOn,
Summary = o.Summary
}).ToList();
Run Code Online (Sandbox Code Playgroud)
但是,一旦我将新的动作列表传递给我的强类型视图,它就失去了它是一个活动还是一个事件的范围,因为它被强制转换为动作.我的问题是,在没有暴露鉴别器列的情况下,有没有办法将每个项目转换为正确的类型,或者我是以错误的方式进行此操作?
有点kludgy,但会工作:
var result = from a in new DataContext().Actions
where a.UserId == someGuidValue
let IsEvent = a as Event != null
select new { a.CreatedOn, IsEvent, a.Summary };
List<Action> list = result.AsEnumerable()
.Select(o => o.IsEvent ?
(Action) new Event {
CreatedOn = o.CreatedOn,
Summary = o.Summary
}
: (Action) new Activity {
CreatedOn = o.CreatedOn,
Summary = o.Summary
}
}).ToList();
Run Code Online (Sandbox Code Playgroud)
具有特定于类型的列的示例,假设e.EventSpecific属于可空类型.
var result = from a in new DataContext().Actions
where a.UserId == someGuidValue
let ev = a as Event
let IsEvent = ev != null
select new { a.CreatedOn, IsEvent, a.Summary, ev.EventSpecific };
List<Action> list = result.AsEnumerable()
.Select(o => o.IsEvent ?
(Action) new Event {
CreatedOn = o.CreatedOn,
Summary = o.Summary,
EventSpecific = o.EventSpecific
}
: (Action) new Activity {
CreatedOn = o.CreatedOn,
Summary = o.Summary,
EventSpecific = o.EventSpecific // will be null, but using o.EventSpecific saves casting
}
}).ToList();
Run Code Online (Sandbox Code Playgroud)
如果o.EventSpecific属于非可空类型,则必须在L2E查询中将其转换为可空类型.
| 归档时间: |
|
| 查看次数: |
15696 次 |
| 最近记录: |