在基类参数被 new 关键字隐藏的模型上运行 EntitySet<> 时可能出现 ODataConventionModelBuilder 错误

问题描述 投票:0回答:1

考虑 Microsoft 示例项目对象的基类 WeatherForcast:

public enum CloudType { A = 1, B = 2 } 

public class WeatherForecastBase { public int CloudType { get; set; }} 

public class WeatherForecast : WeatherForecastBase { 

    public Guid Id { get; set; }
    
    public DateTime Date { get; set; }
    
    public int TemperatureC { get; set; }
    
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    
    public string Summary { get; set; }
    
    public virtual Person WeatherPerson { get; set; }
    
    public virtual IList<Location> Locations { get; set; }
    
    public virtual Location Location { get; set; }
    
    public Address Address { get; set; }
    
    public bool IsCloudy { get; set; }
    
    public new CloudType CloudType { get; set; } }

CloudType
(int)属性被子类隐藏,新属性也改变了它的类型(
CloudType
枚举)。有没有办法让
ODataConventionModelBuilder
成功构建 WeatherForecast 模型并忽略
CloudType
的基类版本?在我的用例中,我收到有关属性必须是原始类型的错误。

c# odata
1个回答
0
投票

我尝试使用通用类型,这可能是你的解决方法:

 public class WeatherForecastBase<T>  {  public virtual T CloudType { get; set; } }

 public class WeatherForecast<T> : WeatherForecastBase<T>
 {

     public Guid Id { get; set; }

     public DateTime Date { get; set; }

     public int TemperatureC { get; set; }

     public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

     public string? Summary { get; set; }

     public bool IsCloudy { get; set; }

    
 }

在 Program.cs 中:

var modelBuilder = new ODataConventionModelBuilder();    
modelBuilder.EntitySet<WeatherForecast<CloudType>>("WeatherForecast");
builder.Services.AddControllers().AddOData(
    options => options.Select().Filter().OrderBy().Expand().Count().SetMaxTop(null).AddRouteComponents(
        "odata",
        modelBuilder.GetEdmModel()));
© www.soinside.com 2019 - 2024. All rights reserved.