【发布时间】:2022-08-13 20:40:50
【问题描述】:
我正在使用带有实体框架和 LINQ 的 .Net 框架 4.7.3。
我正在尝试使用 LINQ 使用两个子类之一从数据库中填充一个新类,但是我遇到了我正在使用的语法错误,并且想知道如何才能绕过它。
错误是
CS8400:功能“目标类型条件表达式”在 C#7.3 中不可用
这是一个简化但完整的版本:
LINQ 查询(问题):
return repo.Find() // Proprietary method returning IQueryable<T> .Select(x => new PostSnippet { Route = x.HasParams ? new DynamicDbRoute { // Properties } : new StaticDbRoute { // Properties } });我想要填充的类:
public sealed class PostSnippet { public string AltText { get; internal set; } public string AnchorText { get; internal set; } public string Image { get; internal set; } public int PostCount { get; internal set; } public string Title { get; internal set; } public IDbRoute Route { get; internal set; } }界面:
public interface IDbRoute { string Url { get; } }类变体:
internal sealed class DynamicDbRoute : DbRoute, IDbRoute { internal int NodeId { get; set; } internal ICollection<RouteParam> RouteParams { get; set; } internal string TopicName { get; set; } public override string GetRouteUrl() { // Implementation } } internal sealed class StaticDbRoute : DbRoute, IDbRoute { public override string GetRouteUrl() { // Implementation } }基类:
internal abstract class DbRoute { private string _url; public string Url => _url ?? (_url = GetRouteUrl()); public string RouteName { get; set; } public abstract string GetRouteUrl(); }我目前正试图让它工作,所以它可能不是完美的解决方案 - 随意加入 - 但主要我需要为查询找到一个可行的解决方案。任何帮助表示赞赏
-
你不能在调用数据库之前输入
?:吗? -
@tymtam - 不太清楚你的意思,但你当然可以这样做: ContentPhysicalFile = x.ContentBlock != null ? x.ContentBlock.PhysicalFile :默认
-
不能移动到 C#9 或 10?
-
@McNets,不确定涉及什么,但听起来这超出了我的职权范围。