EF Core一对多关系配置
- 创建文章、评论实体类 ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace EFCoreRelation.Models { public class Article { public long ID { get; set; } public string Title { get; set; } public string Content { get; set; }
public List<Comment> Comments { get; set; } = new List<Comment>();
}
}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace EFCoreRelation.Models { public class Comment { public long ID { get; set; }
public string Message { get; set; }
public Article Article { get; set; }
}
}
- 安装Nuget包
Microsoft.EntityFrameworkCore.SqlServer<br />Microsoft.EntityFrameworkCore.Tools
- 创建配置类,实现一对多的外键配置,下面尤其要注意评论配置类。
**多个评论有一篇文章(HasOne<Article>(c=>c.Article),一篇文章拥有多个评论(WithMany<Comment>(a=>a.Comments))**
```csharp
using EFCoreRelation.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EFCoreRelation.Configs
{
public class ArticleConfig : IEntityTypeConfiguration<Article>
{
public void Configure(Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder<Article> builder)
{
builder.ToTable("T_Article");
builder.Property(a => a.Content).IsRequired();
builder.Property(a => a.Title).IsRequired().IsUnicode().HasMaxLength(255);
}
}
}
using EFCoreRelation.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EFCoreRelation.Configs
{
public class CommentConfig : IEntityTypeConfiguration<Comment>
{
public void Configure(Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder<Comment> builder)
{
builder.ToTable("T_Comment");
builder.Property(c => c.Message).IsRequired().IsUnicode();
builder.HasOne<Article>(c => c.Article).WithMany(a => a.Comments).IsRequired();
}
}
}
- 创建AlbertDbContext ```csharp using EFCoreRelation.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace EFCoreRelation.DbContexts { public class AlbertDbContext:DbContext { public DbSet
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(connectionString: "Server=.;Database=Albertefcore;" +
"Trusted_Connection=True;MultipleActiveResultSets=true");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
}
}
}
- 执行数据库迁移
```csharp
Add-Migration "Init SQLServer"
Update-Database
- 查看数据库是否有数据(如果配置正常则已有数据)
- 向数据库中插入值 ```csharp using EFCoreRelation.DbContexts; using EFCoreRelation.Models; using Microsoft.EntityFrameworkCore;
// 插入值 //Article article = new Article(); //article.Title = “微软.NET最新动态”; //article.Content = “微软发布了最新的.NET7 Preview版本,该版本优化了JWT配置”; //Comment comment1 = new Comment() { Message = “真的好棒” }; //Comment comment2 = new Comment() { Message = “终于优化了JWT了” }; //Comment comment3 = new Comment() { Message = “拥抱开源后微软变得很牛” }; //Comment comment4 = new Comment() { Message = “巨硬无敌” }; //article.Comments.Add(comment1); //article.Comments.Add(comment2); //article.Comments.Add(comment3); //article.Comments.Add(comment4); //using var ctx = new AlbertDbContext(); //ctx.Articles.Add(article); //await ctx.SaveChangesAsync();
// 移除全部数据 //using var ctx = new AlbertDbContext();
//foreach (var item in ctx.Articles) //{ // ctx.Articles.Remove(item); //} //ctx.SaveChanges();
// 注意SingleOrDefault返回空值的情况 using var ctx = new AlbertDbContext(); try { var articlesingle = ctx.Articles.Include(a => a.Comments).SingleOrDefault(c => c.ID == 4); foreach (var item in articlesingle.Comments) { Console.WriteLine(item.Message); }
} catch (Exception ex) { throw ex; }
```