EF Core-对于ID为0的具有外键的实体,返回null

时间:2018-06-21 13:53:54

标签: c# odata entity-framework-core automapper asp.net-core-2.0

我正在使用来自第三方(仅具有读取权限)的数据库,该数据库具有可空列,该列是另一个表的外键:

Person.Id    1-*    PatientFile.PatientId
PatientFile.PrescDocID    0...1 - 0...1    Person.Id

添加到URL时,我正在使用OData克隆(https://github.com/trenoncourt/AutoQueryable)来获取相关数据:?select = *

问题是可为空的列(Person.Id)有时包含id 0而不是null。这意味着PrescDoc属性在JSON响应中显示为

"prescDoc": {
   "surName": null,
   "firstName": null,
   "isNaturalPerson": null,
   "birthDate": null,
   "id": 0
}

应为:

"prescDoc": null

如果prescDoc对象的ID或PatientFile.PrescDocId id为0,是否可以将EF Core配置为将PatientFile上的属性prescDoc设置为null?

我正在使用的版本:

  • ASP.NET Core 2.1.1
  • EF Core 2.1.1
  • 在MSSQL 2008R2上运行的数据库
  • 在Windows Server 2016上运行的Web服务器

2 个答案:

答案 0 :(得分:1)

其他一些选择:

在您的实体类中,您可以覆盖getter:

private int? prescDocID;
public int? PrescDocID
{
    get => prescDocID == 0 ? default : prescDocID;
    set => prescDocID = value;
}

或者,您可以在序列化期间使用自定义的JsonConverter对其进行控制:

public class ZeroToNullConverter : JsonConverter<int?>
{
    public override int? ReadJson(JsonReader reader, Type objectType, int? existingValue, bool hasExistingValue, JsonSerializer serializer) =>
        reader.Value as int? == 0 ? default : reader.Value as int?;

    public override void WriteJson(JsonWriter writer, int? value, JsonSerializer serializer) =>
        writer.WriteValue(value == 0 ? default : value); 
}

然后:

[JsonConverter(typeof(ZeroToNullConverter))]
public int? PrescDocID { get; set; }

答案 1 :(得分:0)

如果您使用的是AutoQueryable,则根据他们的文档,您可以覆盖Get方法。因此,您可以使用Select进行覆盖,以便如果id的值为0,则正在构造的Person对象可以具有prescDoc prop null:

[Route("api/[controller]")]
public class UsersController : Controller
{
    [HttpGet]
    [AutoQueryable]
    public IQueryable<Person> Get([FromServices] myDbContext dbContext)
    {
        return dbContext.Person.Select(p => new Person() { 
           --other props go here--, 
           prescDoc = p.prescDoc.Id == 0 ? null: p.prescDoc 
           } 
           );
    }
}
相关问题