簡體   English   中英

EF Core,忽略從基礎 class 繼承的 model 字段

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM