How do you add the equivalent of the OwnedAttribute using FluentAPI?

让人想犯罪 __ 提交于 2019-12-01 23:26:08

问题


I can't seem to do this without using either the attribute on TrackState or specifying OwnsOne for Publishers + Articles. Is there any way i can globally mark TrackState as an owned type without using the attribute?

(for people comming through google: How do you add attributes to entities using fluent api?)

(Entities + EF core are in seperate libraries and i do not want a dependency there on 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:


You can use one of the ModelBuilder.Owned method overloads:

modelBuilder.Owned<TrackState>();

or

modelBuilder.Owned(typeof(TrackState));


来源:https://stackoverflow.com/questions/53730130/how-do-you-add-the-equivalent-of-the-ownedattribute-using-fluentapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!