我使用EF从Cosmos DB中插入和检索对象。然而,我的对象及其嵌套子对象将作为单独的文档保存到cosmos中,而不是同时保存在同一个文档中。
我有以下对象
public class Author
{
public Guid AuthorId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public List<Book> Books { get; set; }
}
public class Book
{
public Guid BookId { get; set; }
public string Title { get; set; }
public Author Author { get; set; }
}和下面的DbContext
public class BookStoreDbContext:DbContext
{
private static readonly string EndpointUri = ConfigurationManager.AppSettings["EndPointUri"];
private static readonly string PrimaryKey = ConfigurationManager.AppSettings["PrimaryKey"];
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseCosmos(
EndpointUri,
PrimaryKey,
databaseName: "BookStoreDb");
}
public DbSet<Author> Authors { get; set; }
public DbSet<Book> Books { get; set; }
}这是用于插入数据的代码
using (var context = new BookStoreDbContext())
{
context.Database.EnsureCreated();
var authors = new List<Author>
{
new Author
{
AuthorId = Guid.NewGuid(),
FirstName ="Meredith",
LastName ="Alonso",
BirthDate = DateTime.Parse("1970-09-01"),
Books = new List<Book>()
{
new Book { BookId=Guid.NewGuid(), Title = "Introduction to Microeconomics"}
}
}
};
context.Authors.AddRange(authors);
context.SaveChanges();
}然后,我将一个Author对象和一个Book对象保存到db中,而不是包含嵌套的Book对象的Author对象。
我做错了什么?
发布于 2021-09-24 12:21:05
如果想要嵌套对象,则需要使用owned entities
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
modelBuilder.Entity<Author>().OwnsOne(a => a.Book);
}发布于 2021-09-24 08:29:26
我已经意识到我对EF如何与宇宙合作的理解是缺乏的。
EF拆分对象并将它们保存为单独的文档,尽管它们是父对象的子对象。
因此,对象被拆分的事实并不是bug,而是EF处理宇宙的方式。
https://stackoverflow.com/questions/69303956
复制相似问题