不符合命名约定数据库的 EF 6 外键关系

问题描述 投票:0回答:1

我有两张桌子:

Products
Files

Products
表包含引用
photo_id
表的 FK 列
file_id
(不是
Files
)。

预期结果:我正在尝试获取

Products
及其各自照片的列表。

Product
班级:

[Table("products")]
public partial class Product : Base
{
    [Key]
    [Column("id")]
    public int? Id { get; set; }

    [Column("name")]
    public string Name { get; set; }

    [Column("photo_id")]
    public int? PhotoId { get; set; }

    public virtual File Photo { get; set; }
}

File
班级:

[Table("files")]
public partial class File : Base
{
    [Key]
    [Column("id")]
    public int? Id { get; set; }

    [Column("filename")]
    public string Filename { get; set; }
}

DbContext
类,
OnModelCreating
方法:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);
}

查询时...

public async Task<IEnumerable<Product>> Get()
{
    List<Product> rows;

    rows = await _context.Product
                         .Include(p => p.Photo)
                         .ToListAsync<Product>();
    return rows;
}

我收到此错误消息:

“ClassName”:“Npgsql.PostgresException”,
"Message": "42703: 列 f.ProductId 不存在",
“数据”:{
“严重性”:“错误”,
“不变严重性”:“错误”,
“SqlState”:“42703”,
"MessageText": "列 f.ProductId 不存在",
“位置”:987,
“文件”:“parse_relation.c”,
“线路”:“3643”,
“例程”:“错误缺少列”
},

为什么 EF 希望我的

File
表有
ProductId
列?如何避免这种情况?

我正在使用 .NET 6、EF 6 和 Postgres。

我尝试添加

ForeignKey
注释,如下所示:

//[ForeignKey("photo_id")]
public virtual File Photo { get; set; }

...但这并不能解决问题。有什么想法吗?

c# postgresql entity-framework-core linq-to-entities
1个回答
0
投票

您将属性名称 PhotoId 更改为 photo_id,违反了发现外键和关系的默认约定。

您有多种方法可以解决此问题:

  • OnModelCreating函数中,您可以明确告诉EF核心photo属性的photoId是FK 示例:

    modelBuilder.Entity().HasOne(x => x.Photo).WithOne();

  • 您可以删除 Column["photo_id"] 属性,然后 EF core 可以自动发现关系。

您可以阅读有关 EF core 中关系发现约定的更多信息这里 & 这里

© www.soinside.com 2019 - 2024. All rights reserved.