分类:
Net Core
第一步: 找到appsettings.json这个文件,修改如下: { "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "ConnectionStrings": { "BloggingDatabase": "Server=.;Database=数据库名称;Trusted_Connection=True;" } } 第二步: 创建一个类继承DbContext, using Microsoft.EntityFrameworkCore; using Model; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace DAL { public class CoreFirst_DbContext: DbContext { public CoreFirst_DbContext(DbContextOptions<CoreFirst_DbContext> options) : base(options) { } public DbSet<Post> Posts { get; set; } public DbSet<Tag> Tags { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); } protected override void OnModelCreating(ModelBuilder modelBuilder) { //唯一约束,替代键 modelBuilder.Entity<PostTag>() .HasKey(pt => new { pt.PostId, pt.TagId }); modelBuilder.Entity<PostTag>() .HasOne(pt => pt.Post) .WithMany(p => p.PostTags) .HasForeignKey(pt => pt.PostId); modelBuilder.Entity<PostTag>() .HasOne(pt => pt.Tag) .WithMany(t => t.PostTags) .HasForeignKey(pt => pt.TagId); } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public List<PostTag> PostTags { get; set; } } public class Tag { public int TagId { get; set; } public string remark { get; set; } public List<PostTag> PostTags { get; set; } } public class PostTag { public int PostId { get; set; } public Post Post { get; set; } public int TagId { get; set; } public Tag Tag { get; set; } } } 第三步:找到Startup.cs这个文件,找到它下面的ConfigureServices方法并添加 services.AddDbContext<CoreFirst_DbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase"))); 第四步:然后添加数据迁移,更新数据库,就完成了多对多关系数据库的配置。
评价
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术