【问题标题】:How to map a column from another table?如何映射另一个表中的列?
【发布时间】:2020-04-02 08:38:48
【问题描述】:

我有两个表 articlescontent(一对一关系)。 content 表包含 JSON 格式 (PostgreSQL) 的文章正文。出于性能原因,表格被拆分,因为内容太大。

文章表:

| Column          | Type   |
|-----------------|--------|
| id              | int    |
| title           | string |
| *other columns* | xxx    |

内容表:

| Column    | Type  |
|-----------|-------|
| articleId | int   |
| content   | jsonb |

我正在尝试将这些表映射到单个实体 Article

namespace Domain.Models
{
    [Table("articles")]
    public class Article
    {
        [Column("id")]
        public int Id { get; set; }

        [Column("title")]
        public string Title { get; set; }

        [Column("content")]
        public string Content { get; set; }

        <...> // other columns
    }
}

我的DbContext

namespace Domain
{
    public class MasterDbContext : DbContext
    {
        public DbSet<Article> Articles { get; set; }
    }
}

问题: 如何从content 表映射Content 属性?


我的愚蠢解决方案:我刚刚创建了一个非物化视图并将Article 实体映射到这个“表”:

CREATE VIEW articles_with_content AS
    SELECT a.*, c.content
    FROM articles AS a
    JOIN content AS c ON c."articleId" = a.id;

有人可以提出更好的解决方案吗?

【问题讨论】:

    标签: c# postgresql entity-framework database-design entity-framework-core


    【解决方案1】:

    你需要创建一个 Content 类

    然后在您的文章类中将其设置为:

    public Content Content { get; set; }
    

    然后配置您的模型(在您的 MasterDbContext 类中)

    protected override void OnModelCreating(ModelBuilder builder)
             {
                builder.Entity<Article>(b =>
                {
                    b.HasOne(c => c.Content)
    
                   .WithOne(a => a.Article)
    
                   .HasForeignKey<Content>(d => d.ArticleID);
                });
    
             }
    

    【讨论】:

    • 但在这种情况下,Content 属性将是一个对象,而不是一个字符串
    • 对,你会像这样访问文章内容:article.Content.Content
    猜你喜欢
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 2012-08-16
    相关资源
    最近更新 更多