【问题标题】:How to define relationships on ef core 3?如何定义 ef core 3 上的关系?
【发布时间】:2021-01-06 09:04:22
【问题描述】:

我是 .net core 和 ef 方面的初学者,我想就我正在做的一个小项目(.Net Core WebApi)获得一些帮助

为了澄清我在这里做什么是图表:

这是我作为模型类编写的代码:

所有代码是否正确代表了我尝试做的事情?我是否必须先声明像 id 这样的道具,然后使用 [ForeignKey] 注释声明其他类类型的道具? 另外例如,如果我想使用字符信息进行发布请求,我应该像这样发送 json 吗?:

{
    "Name":"Lost Vayne Meliodas",
    "Awaken":6,
    "Level":80,
    "AttributeId":1,
    "RarityId":4
}

谢谢!

【问题讨论】:

    标签: entity-framework .net-core asp.net-core-webapi


    【解决方案1】:

    您应该使用 FluentAPI。

    在您的 dbcontext 类中,您应该有 3 个 dbset,如下所示

    public DbSet<Character> Character { get; set; }
        public DbSet<Rarity> Rarity { get; set; }
        public DbSet<Attribute> Attribute { get; set; }
        
        //You need to have a OnModelCreating method in the same dbcontext class
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
                {
                    
                    base.OnModelCreating(modelBuilder);
                     modelBuilder.Entity<Rarity>()
                         .HasMany(c => c.Characters)
                         .WithOne(e => e.Rarity);
                   modelBuilder.Entity<Attribute>()
                         .HasMany(c => c.Characters)
                         .WithOne(e => e.Attribute);
        
        }
    

    将此添加到您的稀有度表中

    public ICollection<Character> Characters { get; set; }
    

    将此添加到您的属性表中

    public ICollection<Character> Characters { get; set; }
    

    【讨论】:

    • 感谢您的建议!另外,使用 FluentApi 比使用数据注释更好吗?另外,我为什么要将该系列添加到属性和稀有度中?通过字符获取它们不是更好吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2021-05-20
    相关资源
    最近更新 更多