1. 程式人生 > >在efcore 中創建類 通過實現IEntityTypeConfiguration<T>接口 實現實體類的夥伴類 實現FluentApi

在efcore 中創建類 通過實現IEntityTypeConfiguration<T>接口 實現實體類的夥伴類 實現FluentApi

nbsp tab ont part get inf 9.png void nconf

1 創建實體類:

 public partial class NewsCategory : IAggregationRoot
    {
        public NewsCategory() { }
        public Guid Id { get; set; }
        public string CategoryName { get; set; }
        public bool IsDel { get; set; }
        public string Code { get; set; }
    }

2.創建實體類的映射夥伴類

public class
NewsCategoryMap : IEntityTypeConfiguration<NewsCategory> { public void Configure(EntityTypeBuilder<NewsCategory> builder) { builder.ToTable("NewsCategory"); } }

3.在上下文中 重寫 OnModelCreating方法 將夥伴類的應用上

 public class NewsEFCoreContext:DbContext,INewsContext
    {
       
        
public DbSet<NewsCategory> Categories { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //先直接寫連接字符串,生成數據庫。後續再在配置文件中配置,並使用到此處 optionsBuilder.UseSqlServer("Server=localhost;Database=wehope;User ID=sa;Password=0");
//optionsBuilder.UseSqlServer(AppSetting.GetAppSetting("DealerContext")); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfiguration<NewsCategory>(new NewsCategoryMap()); base.OnModelCreating(modelBuilder); } }

完成。

技術分享圖片

在efcore 中創建類 通過實現IEntityTypeConfiguration<T>接口 實現實體類的夥伴類 實現FluentApi