如何解决编辑数据库上下文以从相关实体获取名称
我是VS2019,EF和.net Core 3.1的新手,所以请与我同在。
dbcontext
modelBuilder.Entity<Books>(entity =>
{
entity.Property(e => e.Id).HasColumnName("id");
entity.Property(e => e.Createdon)
.HasColumnName("createdon")
.HasColumnType("datetime")
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.Goal)
.HasColumnName("goal")
.HasMaxLength(100)
.IsUnicode(false);
entity.Property(e => e.Grade)
.HasColumnName("grade")
.HasMaxLength(2)
.IsUnicode(false);
entity.Property(e => e.Subjectid).HasColumnName("subjectid");
entity.HasOne(d => d.Subject)
.WithMany(p => p.Books)
.HasForeignKey(d => d.Subjectid)
.HasConstraintName("FK_Books_Subjects");
});
modelBuilder.Entity<Subjects>(entity =>
{
entity.Property(e => e.Id).HasColumnName("id");
entity.Property(e => e.Createdby).HasColumnName("createdby");
entity.Property(e => e.Name)
.HasColumnName("name")
.HasMaxLength(50)
.IsUnicode(false);
});
在这里,我想在检索“图书”时从“主题”实体获取主题名称。 不幸的是,我没有EF Desginer模型可用(不知道为什么)。 是否可以通过dbcontext做到这一点?
解决方法
因此,Book与Subject之间存在一对多的关系:每本Book都有一个主题,即外键SubjectId所引用的主题。每个主题都是零本或更多本图书的主题。
现在,您需要书籍(的某些属性),每本书及其主题名称以及其他一些主题属性。
如果您的Book类具有属性virtual Subject Subject {get; set;}
,则可以使用该属性来获取它。实体框架知道一对多关系,并且知道如何将其转换为适当的(Group-)Join。
如果类不具有此属性,则应执行“自己加入”:
使用虚拟属性
class Subject
{
public int Id {get; set;}
...
// Every Subject is the subject of zero or more Books (one-to-many)
public virtual ICollection<Book> Books {get; set;}
}
class Book
{
public int Id {get; set;}
...
// Every Book has exactly one Subject,using foreign key:
public int SubjectId {get; set;}
public virtual Subject Subject {get; set;}
}
这是实体框架检测到一对多关系所需了解的所有信息。
var booksWithTheirSubjectNames = dbContext.Books
// only if you don't want all Books
.Where(book => ...)
.Select(book => new
{
// Select the Book properties that you plan to use:
Id = book.Id,Title = book.Title,...
// Select the subject properties that you plan to use
Subject = new
{
Name = book.Subject.Name,Description = book.Subject.Description,...
},});
加入自己的行列
如果您具有一对多关系,那么您将具有单边和多边关系。要获取“带有零个或多个子项的项目”,请使用GroupJoin
;要获取“具有外键引用的唯一父项的项目”,请使用Join
。
var booksWithTheirSubjectNames = dbContext.Books.Join(dbContext.Subjects,book => book.SubjectId,// from every Book take the foreign key
subject => subject.Id,// from every Subject take the primary key
// when they match,take the Book and the Subject to make one new object:
(book,subject) => new
{
Id = book.Id,...
Subject = new
{
Name = book.Subject.Name,});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。