c# - 如何使用 Fluent API 添加等效的所有者属性?

标签 c# entity-framework-core ef-core-2.1

如果不使用 TrackState 上的属性或为 Publishers + Articles 指定 OwnsOne,我似乎无法做到这一点。有什么方法可以在不使用属性的情况下将 TrackState 全局标记为拥有类型?

(对于通过 google 访问的人:如何使用 fluent api 向实体添加属性?)

(实体 + EF 核心在单独的库中,我不希望那里依赖于 EF)

public class Publisher
{
    public int Id { get; set; }

    public string Name { get; set; }

    public virtual ICollection<Article> Articles { get; set; } = new List<Article>();

    public TrackState State { get; set; }
}

public class TrackState
{
    public DateTime? Created { get; set; }

    public DateTime? Modified { get; set; }
}

public class Article
{
    public int Id { get; set; }

    public int PublisherId { get; set; }

    public string Content { get; set; }

    public TrackState State { get; set; }
}


public class CustomContext : DbContext
{
    public CustomContext()
    {
    }

    public CustomContext(DbContextOptions options) : base(options)
    {
    }

    public DbSet<Publisher> Publishers { get; set; }

    public DbSet<Article> Articles { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=BananaDb;Trusted_Connection=True;");
        //          base.OnConfiguring(optionsBuilder);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // one of the attempts i would have expected to work.
        modelBuilder.Entity<TrackState>().HasAnnotation("Owned", true);
        base.OnModelCreating(modelBuilder);
    }
}

最佳答案

您可以使用 ModelBuilder.Owned 之一方法重载:

modelBuilder.Owned<TrackState>();

modelBuilder.Owned(typeof(TrackState));

关于c# - 如何使用 Fluent API 添加等效的所有者属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53730130/

相关文章:

c# - 英孚模型。导航属性只能参与单个关系

mysql - 使用 EFCore 在多个表中选择

c# - 如何在自定义验证属性中访问 View 模型的属性值以更改消息?

c# - 列表优化不稳定

c# - EF 6 Code First From Database - 调用现有的存储过程

C# 将一个图像区域复制粘贴到另一个图像中

c# - 使用 EF Core 在通用存储库中包含所有使用反射的导航属性

c# - Entity Framework Core - .Contains() - 为什么转义而不是参数化?

c# - 在 EFCore 中的单个 LINQ 查询中获得 2 个前 5 个

oracle - oracle 数据库中特定表的脚手架 dbcontext 抛出与该表无关的错误