Mas*_*240 0 c# entity-framework ef-code-first
我在使用GetType()和typeof()获得类的类型时遇到问题,问题在于它无法正常工作。
我有Content的基类和Podcast和AudioBook的继承类。
我使用的是Code First,并且每个层次结构都有一个表(该表将所有子类存储在一个带有Discriminator列的表中)来存储所有Content实体。
我想通过“标题”列查询“内容”表,并返回一个“内容”实体。然后,根据类型(Podcast,AudioBook)执行其他操作。但是类型检查不起作用。
楷模
public abstract class Content
{
public string Title { get; set; }
}
public class Podcast : Content
{
}
Run Code Online (Sandbox Code Playgroud)
资料库
public Content FindContentByRoutingTitle(string routingTitle)
{
var content = Context.ContentItems
.FirstOrDefault(x => x.RoutingTitle == routingTitle);
return content;
}
Run Code Online (Sandbox Code Playgroud)
控制者
var content = _contentRepository.FindContentByRoutingTitle(title);
if (content.GetType() == typeof(Podcast))
{
return RedirectToAction("Index", "Podcast", new { title = title });
}
else if (content.GetType() == typeof(Content))
{
//just a check to see if equating with Content
return RedirectToAction("Index", "Podcast", new { title = title });
}
else
{
//if/else block always falls to here.
return RedirectToAction("NotFound", "Home");
}
Run Code Online (Sandbox Code Playgroud)
我在这里缺少什么吗?谢谢你的帮助。
GetType()返回实际对象的类别,所以如果你试图把它比typeof(Content)你会得到false。但是,如果要检查变量是否派生自基类,则建议使用2个选项。
选项1:
if (content is Content)
{
//do code here
}Run Code Online (Sandbox Code Playgroud)选项2:
if (content.GetType().IsSubclassOf(typeof(Content)))
{
//do code here
}Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
1102 次 |
| 最近记录: |