c# - 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);
解决方案
您已经像这样声明了变量:Author author = new Organization
因此您的变量将是类型Author
- 它没有“名称”属性。
您可能需要重新审视您在这里的工作方式。您可以简单地将变量声明为Organisation author = new Organisation
. 但如果不猜测,很难知道更多。
[OT:我的 2 美分价值——不要过度使用继承。可以从一些重复的代码开始,然后你可以看到模式出现并重构。]
推荐阅读
- javascript - React @reach/Router 问题如何使开关柜工作
- c++ - 从 std::function 推导出模板参数
- php - 我不断收到“调用未定义函数..”错误显示
- python - pyspark 数据框从一列字符串中提取每个不同的单词并将它们放入一个新的数据框
- python - 尝试使用 pyodbc 将 python 连接到 Access 数据库时出错
- python - Selenium 无法通过 ID 定位元素
- php - 内含
- javascript - 有没有办法向用户编码指令,其中包括他们输入的信息?
- sql - 当数据透视表的 IN 子句中的每个 id 恰好有一条记录时,查询返回一条记录
- r - 寻找有关格式化 Rmarkdown 数据透视表的建议