首页 > 其他分享 >EF Core 关系配置

EF Core 关系配置

时间:2023-11-06 19:56:02浏览次数:37  
标签:Core 配置 Name get builder EF set new public

一、一对多

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>(); //此文章的若干条评论
}
public class Comment
{
    public long Id { get; set; }
    public Article Article { get; set; }//导航属性
    public long ArticleId { get; set; }// 声明ArticleId是考虑到有时候不连表查询且需要查询ArticleId
    public string Message { get; set; }
}

  1、配置

class ArticleConfig : IEntityTypeConfiguration<Article>
{
    public void Configure(EntityTypeBuilder<Article> builder)
    {
        builder.ToTable("T_Articles");
        builder.Property(a => a.Content).IsRequired().IsUnicode();
        builder.Property(a => a.Title).IsRequired().IsUnicode().HasMaxLength(255);
    }
}

  

class CommentConfig : IEntityTypeConfiguration<Comment>
{
    public void Configure(EntityTypeBuilder<Comment> builder)
    {
        builder.ToTable("T_Comments");
        builder.HasOne<Article>(c => c.Article).WithMany(a => a.Comments)//这里使用的双向导航属性。如何使用单向导航属性:HasOne<Article>(t=>t.Article).WithMany()
            .IsRequired().HasForeignKey(c => c.ArticleId);//不指定HasForeighKey,数据库中会生成两个ArticleId
        builder.Property(c => c.Message).IsRequired().IsUnicode();
    }
}

 

  2、数据插入

using MyDbContext ctx = ew MyDbContext();

Article a1 = new Article();
a1.Title="TESIJTISJIOT";
a1.Content="jsdfiiiiiiiiiiiiiiiiiiiiiiiCONTiejwqitoniosjfiosadnvocijiotads----";

Comment c1 = new Comment{Message="niubi"};
Comment c2 = new Comment{Message="tailnisjfis"}

a1.Comments.Add(c1);
a1.Comments.Add(c2);

ctx.Articles.Add(a1);
ctx.SaveChanges();

  3、数据获取

using MyDbContext ctx = new MyDbContext();
Airticle a= ctx.Articles.Include(a-=>a.Comments).Single(a=>a.ID==1);
Console.WriteLine(a.Title);
foreach(Comment c in a.Comments) { Console.WriteLine(c.Id + ":" + c.Message); }
using MyDbContext ctx = new MyDbContext();
var cs= ctx.Comments.Include(a-=>a.Airticle).Where(a=>a.AirticleId==1).ToList();

foreach(Comment c in cs)
{
    Console.WriteLine(c.Airticle.Title);
    Console.WriteLine(c.Id + ":" + c.Message);
 }  

 二、一对一

class Delivery
{
    public long Id { get; set; }
    public string CompanyName { get; set; }//快递公司名
    public String Number { get; set; }//快递单号
    public Order Order { get; set; }//订单
    public long OrderId { get; set; }//指向订单的外键
}

class Order
{
    public long Id { get; set; }
    public string Name { get; set; }//商品名
    public string Address { get; set; }//收货地址
    public Delivery? Delivery { get; set; }//快递信息
}

  1、配置

class DeliveryConfig : IEntityTypeConfiguration<Delivery>
{
    public void Configure(EntityTypeBuilder<Delivery> builder)
    {
        builder.ToTable("T_Deliveries");
        builder.Property(d => d.CompanyName).IsUnicode().HasMaxLength(10);
        builder.Property(d => d.Number).HasMaxLength(50);
    }
}
class OrderConfig : IEntityTypeConfiguration<Order>
{
    public void Configure(EntityTypeBuilder<Order> builder)
    {
        builder.ToTable("T_Orders");
        builder.Property(o => o.Address).IsUnicode();
        builder.Property(o => o.Name).IsUnicode();
        builder.HasOne<Delivery>(o => o.Delivery).WithOne(d => d.Order)
            .HasForeignKey<Delivery>(d => d.OrderId);
    }
}

  2、数据插入

using TestDbContext ctx = new TestDbContext();
Order order = new Order();
order.Address = "北京市海淀区中关村南大街999号";
order.Name = "USB充电器";
Delivery delivery = new Delivery();
delivery.CompanyName = "蜗牛快递";
delivery.Number = "SN333322888";
delivery.Order = order;
ctx.Deliveries.Add(delivery);
await ctx.SaveChangesAsync();

  3、数据获取

Order order1 = await ctx.Orders.Include(o => o.Delivery)
    .FirstAsync(o => o.Name.Contains("充电器"));
Console.WriteLine($"名称:{order1.Name},单号:{order1.Delivery.Number}");

三、多对多

class Student
{
    public long Id { get; set; }
    public string Name { get; set; }
    public List<Teacher> Teachers { get; set; } = new List<Teacher>();
}

class Teacher
{
    public long Id { get; set; }
    public string Name { get; set; }
    public List<Student> Students { get; set; } = new List<Student>();
}

  1、配置

class StudentConfig : IEntityTypeConfiguration<Student>
{
    public void Configure(EntityTypeBuilder<Student> builder)
    {
        builder.ToTable("T_Students");
        builder.Property(s => s.Name).IsUnicode().HasMaxLength(20);
        builder.HasMany<Teacher>(s => s.Teachers).WithMany(t => t.Students)
            .UsingEntity(j => j.ToTable("T_Students_Teachers"));
    }
}

class TeacherConfig : IEntityTypeConfiguration<Teacher>
{
    public void Configure(EntityTypeBuilder<Teacher> builder)
    {
        builder.ToTable("T_Teachers");
        builder.Property(s => s.Name).IsUnicode().HasMaxLength(20);
    }
}

  2、数据插入

Student s1 = new Student { Name = "tom" };
Student s2 = new Student { Name = "lily" };
Student s3 = new Student { Name = "lucy" };
Student s4 = new Student { Name = "tim" };
Student s5 = new Student { Name = "lina" };
Teacher t1 = new Teacher { Name = "杨中科" };
Teacher t2 = new Teacher { Name = "罗翔" };
Teacher t3 = new Teacher { Name = "刘晓艳" };
t1.Students.Add(s1);
t1.Students.Add(s2);
t1.Students.Add(s3);
t2.Students.Add(s1);
t2.Students.Add(s3);
t2.Students.Add(s5);
t3.Students.Add(s2);
t3.Students.Add(s4);
using TestDbContext ctx = new TestDbContext();
ctx.AddRange(t1, t2, t3);
ctx.AddRange(s1, s2, s3, s4, s5);
await ctx.SaveChangesAsync();

  3、数据获取

using TestDbContext ctx = new TestDbContext();
foreach (var t in ctx.Teachers.Include(t => t.Students))
{
    Console.WriteLine($"老师{t.Name}");
    foreach (var s in t.Students)
    {
        Console.WriteLine($"---{s.Name}");
    }
}

Part3-21:EF Core多对多_哔哩哔哩_bilibili

标签:Core,配置,Name,get,builder,EF,set,new,public
From: https://www.cnblogs.com/lixiang1998/p/17811206.html

相关文章

  • 计算机配置 — 管理模板 — Windows 组件 — 数据收集和预览版本 对应 注册表 位置
    @echooff::切换对预览体验成员内部版本的用户控制regadd"HKLM\SOFTWARE\Policies\Microsoft\WindowsPreviewBuilds"/vAllowBuildPreview/tREG_DWORD/d1/f::允许商业数据管道regadd"HKLM\SOFTWARE\Policies\Microsoft\Windows\DataCollection"/vCommerc......
  • Java中的NoClassDefFoundError报错解析
    半夜睡得正香的时候,突然接到警告电话,于是翻起身就打卡电脑连上环境查看是什么情况?登录上之后发现有个微服务占用的句柄数量一直在持续上涨,最终导致了微服务内存溢出挂掉了。这个微服务在运行的过程中会建立SSH连接,且之前这个微服务已经遇到过很多次类似的情况了,因此第一反应是哪里......
  • wpf 记一次诡异的PreviewMouseLeftButtonDown 无法触发问题
    1、原始代码<Grid><i:Interaction.Triggers><i:EventTriggerEventName="PreviewMouseLeftButtonDown">......
  • linux登陆防护fail2ban的优化配置
    fail2ban默认在iptables防火墙filter表的input链内设置规则,这样导致端口映射,和nat转发的流量不在fail2ban控制内。如果修改配置文件/etc/fail2ban/action.d#viiptables-common.conf  把INPUT链修改成FORWARD链后存在同样问题,会导致进入主机的流量不受控。这里需要在IN......
  • datax 配置
    "job":{"setting":{"speed":{"channel":3,"byte":1048576},"errorLimit":{"record":0,"percenta......
  • windows下nginx 配置 开机自启动
    一、windows系统下Nginx安装启动流程:二、设置Nginx开机自动启动1、自启动工具下载2、自启动工具安装3、把nginx加入到windows服务中最后一句话一、windows系统下Nginx安装启动流程:这是我们在正常环境中,Windows下Nginx的安装及启动方式1、到nginx官网下载相应版本(http://nginx.org......
  • JDK 21安装及环境配置
    注意:1、本文的性质为初学者的实操记录,文中内容若与你遭遇的情况不符,请另行寻找更靠谱的教程。比如我参考的就是:“AAA黄豆AAA”的JDK21安装教程2、本文撰写时间为2023年11月6日,操作系统为Windows10家庭版,若时殊事异,请理性对待。一、安装JDK211、从Oracle官网获取JDK21安......
  • Makefile
    0背景在工作中,经常会与makefile打交道,但是有很多的时候,不明白其中的语法意思,这里主要记录一下常遇到的一些语法。一、测试模板很多时候,我们在理解一个知识的时候,有点难理解,我们可以自己写个测试文件来测试下,看看效果,加深理解。$(warningwarning:'thisisaloginfo')TAR......
  • 配置使用百度地图时出现:APP Referer校验失败。请检查该ak设置的白名单与访问所有的域
    如果是个人内部测试使用,直接将IP白名单设置为*  ......
  • GBrowse配置相关资料
    GBrowse配置相关资料(形状、颜色、配置、gff3)http://gmod.org/wiki/Glyphs_and_Glyph_Optionshttp://gmod.org/wiki/GBrowse_Configuration/Glyphshttp://gmod.org/wiki/GBrowse_Configuration/Feature_frequency_histograms(2010)http://boyun.sh.cn/bio/?p=1817(2011 GBrowse之......