ef 更新数据库表结构
One of the very common questions I am getting from .NET
community is how to configure and use the tree structures in EF Core
. This story is one of the possible ways to do it.
我从.NET
社区获得的一个非常常见的问题之一是如何在EF Core
配置和使用树结构。 这个故事是实现它的可能方法之一。
The common tree structures are file tree, categories hierarchy, and so on. Let it be folders tree for example. The entity class will be a Folder
:
常见的树结构是文件树,类别层次结构等。 例如,让它成为文件夹树。 实体类将是Folder
:
public class Folder
{
public Guid Id { get; set; }
public string Name { get; set; }
public Folder Parent { get; set; }
public Guid? ParentId { get; set; }
public ICollection<Folder> SubFolders { get; } = new List<Folder>();
}
This is how to configure DB schema via overriding OnModelCreating
method of your DbContext
class. This could be done via configuration property attributes on our entity class, but I prefer to define DB schema this way.
这是通过覆盖DbContext
类的OnModelCreating
方法配置数据库架构的方法。 这可以通过我们实体类上的配置属性属性来完成,但是我更喜欢以这种方式定义数据库模式。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Folder>(entity =>
{
entity.HasKey(x => x.Id);
entity.Property(x=> x