[英]JSON/XML serialization: Ignore/include some fields from the base class
[英]EF Core, ignore model fields inherited from base class
我在我的应用程序中使用了两个数据库 - 带有 EF Core 的 MySQL 和 Realm,因为它们都使用相同的模型,为了避免混淆,我对它们都使用相同的 model 类:
using System.ComponentModel.DataAnnotations.Schema;
using Realms;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System;
using Realms.Schema;
namespace Data.Models
{
[Table("entry")]
public class Entry : RealmObject
{
public class EntryType
{
public const byte Word = 1;
public const byte Phrase = 2;
public const byte Text = 3;
};
[Key]
[PrimaryKey]
[Column("entry_id")]
public int Id { get; set; }
[Column("user_id")]
public int UserId { get; set; }
[Column("source_id")]
public int SourceId { get; set; }
[Indexed]
[Column("type")]
public byte Type { get; set; }
[Column("rate")]
public int Rate { get; set; }
[Column("created_at")]
public string CreatedAt { get; set; }
[Column("updated_at")]
public string UpdatedAt { get; set; }
[NotMapped]
public Phrase Phrase { get; set; }
[NotMapped]
public Word Word { get; set; }
[NotMapped]
public Text Text { get; set; }
public IList<Translation> Translations { get; }
}
}
对于 EF 核心:
namespace Data.Contexts
{
public class EntryContext : BaseContext
{
public DbSet<Entry> Entries { get; set; }
}
}
它工作正常,但是当与 EF Core 一起使用时,我得到了从 RealmObject 派生的不必要的字段,这是一个问题,因为我正在尝试构建一个 API 并且我不想要我没有明确定义的任何内容
/ https://localhost:44349/entry/randoms
[
{
"id": 34101,
"userId": 1,
"sourceId": 1,
"type": 2,
"rate": -1,
"createdAt": "1/26/2020 9:45:07 AM",
"updatedAt": "4/30/2020 7:18:05 PM",
"phrase": null,
"word": null,
"text": null,
"translations": [],
"content": null,
"isManaged": false,
"isValid": true,
"realm": null,
"objectSchema": null,
"backlinksCount": 0
},
]
我想告诉 EF Core 忽略这些继承的字段而不破坏 Realm 的任何内容:
"isManaged": false,
"isValid": true,
"realm": null,
"objectSchema": null,
"backlinksCount": 0
我怎样才能做到这一点? 或者也许有更好的方法将一个 model 用于两个 ORM?
您可以为此使用 Fluent API
namespace Data.Contexts
{
public class EntryContext : BaseContext
{
public DbSet<Entry> Entries { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Entry>()
.Ignore(e => e.IsManaged)
.Ignore(e => e.IsValid)
//etc.
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.