• EFcore的 基础理解<三> 多对多,唯一约束


    唯一约束,替代键。

     modelBuilder.Entity<Car>()
                .HasAlternateKey(c => new { c.State, c.LicensePlate });

    多对多,可以直接建立,在上层调用的时候比较方便。

    class MyContext : DbContext
    {
        public DbSet<Post> Posts { get; set; }
        public DbSet<Tag> Tags { get; set; }
    
        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 string TagId { get; set; }
    
        public List<PostTag> PostTags { get; set; }
    }
    
    public class PostTag
    {
        public int PostId { get; set; }
        public Post Post { get; set; }
    
        public string TagId { get; set; }
        public Tag Tag { get; set; }
    }
    气功波(18037675651)
  • 相关阅读:
    11.文件操作
    10.模块和包
    9.异常
    8.单例模式
    7.类属性、类方法、静态方法
    小学口算题卡---田青正
    个人技术流程(四则运算)--马伟杰
    个人开发流程(四则运算)--张文龙
    个人技术流程(四则运算)--王潮玉
    个人技术流程(四则运算)--毛明明
  • 原文地址:https://www.cnblogs.com/qgbo/p/11502236.html
Copyright © 2020-2023  润新知