如何使用FluentAPI添加等效于OwnedAttribute的内容?

时间:2018-12-11 18:18:57

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

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

(对于通过Google来的人:如何使用流利的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);
    }
}

1 个答案:

答案 0 :(得分:4)

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

modelBuilder.Owned<TrackState>();

modelBuilder.Owned(typeof(TrackState));