首页 > 解决方案 > EF Core:如何访问另一个相关实体内的派生类中的属性

问题描述

我想从 TPH 中的派生类访问属性。

基类

public abstract class Author
{
    public int AuthorId { get; set; }

    public AuthorType AuthorType { get; set; }

    public ICollection<Post> Posts { get; set; }

}

派生类

public class Organization : Author
{ 
    public string Name { get; set; }

}

配置

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Author>()
                .HasDiscriminator(a => a.AuthorType)
                .HasValue<Person>(AuthorType.Person)
                .HasValue<Organization>(AuthorType.Organization);

    modelBuilder.Entity<Author>()
                .HasMany(p => p.Posts);

    modelBuilder.Entity<Post>()
                .HasOne(a => a.Author)
                .WithMany(p => p.Posts);
}

我想访问组织职位中的属性名称:

Author author = new Organization { Name = "CA", OrganizationType = OrganizationType.NonProfit};

Post post = new Post { Subject = "News", Author = author, Tag = PostTag.SualatUpdate};

context.Add(author);
context.Add(post);

标签: c#entity-framework

解决方案


您已经像这样声明了变量:Author author = new Organization因此您的变量将是类型Author- 它没有“名称”属性。

您可能需要重新审视您在这里的工作方式。您可以简单地将变量声明为Organisation author = new Organisation. 但如果不猜测,很难知道更多。

[OT:我的 2 美分价值——不要过度使用继承。可以从一些重复的代码开始,然后你可以看到模式出现并重构。]


推荐阅读