我想访问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);
答案 0 :(得分:1)
您已经这样声明了变量:Author author = new Organization
,因此您的变量将为Author
类型-该变量不具有'Name'属性。
您可能需要在这里重新查看自己的工作方式。您可以简单地将变量声明为Organisation author = new Organisation
。但是很难不去猜测就知道更多。
[OT:我的2美分价值-不要过度使用继承。可以从一些重复的代码开始,然后再看到模式出现并重构。]