Entity Framework Core 添加视图和标准模型对象之间的关系

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

这是这样的场景:我使用 SQL Server 作为后端,我有一个数据库实例,该数据库包含一些常用表,我想将这些表与新 MVC 应用程序的数据库中的表连接起来。

我们计划拥有数十个 MVC 应用程序,每个应用程序都有其专用的数据库,因此我们希望避免将每个公用表复制到每个新数据库。我想到使用视图来代替。

但我不知道如何添加视图和其他标准模型类之间的关系,以允许我将 EF 与 LINQ 功能一起使用。

这是我迄今为止所做的演示 1 应用程序 - 它适用于 ASP.NET Core 6.0 MVC 以及 EF Core 6.0。

model
文件夹中,我有:

public class Pratica
{
    public int Id { get; set; }        
    public string Note { get; set; }
    public int UtenteId { get; set; }
    public Utente Utente { get; set; } = default!; 
    /* other fields removed for simplicity */   
}

public class Utente
{
     public int Id { get; set; } 
     public string Name { get; set; } = string.Empty;
     public int IdPalazzo     
     public List<Pratica>? Pratiche { get; set; }
    /* other fields removed for simplicity */
}

/* this one represent sthe view */
public class Palazzo
{
    public int IdPalazzo { get; set; }
    public string NomePalazzo { get; set; }
    public string Indirizzo { get; set; }
    /* other fields removed for simplicity */
}

在 demo1 DB 中创建视图 Palazzi 的具体迁移

public partial class commonTabs : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.Sql("CREATE VIEW dbo.Palazzi as select IdPalazzo , NomePalazzo , Indirizzo  from  Common.dbo.Palazzi;");
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.Sql("DROP VIEW dbo.Palazzi;");
    }
}

现在,在 demo1DbContext.cs 中添加了 DBsets

public DbSet<Pratica> Pratiche { get; set; }
public DbSet<Utente> Utenti { get; set; }
public DbSet<Palazzo> Palazzi { get; set; }

但我在这里迷路了。我看到其他帖子建议使用

protected override void OnModelCreating(ModelBuilder modelBuilder)

但我不知道如何实现。

如何使用

Utente
Palazzo
IdPalazzo
加入。关键是视图没有主键。

我想使用 LINQ 在一对一关系中包含从

Palazzi
开始的有关
Utenti
的信息。

sql-server view entity-framework-core asp.net-core-mvc .net-6.0
1个回答
0
投票

要实现设置一对一关系并使用 LINQ 查询的要求,您需要使用

OnModelCreating
来配置关系,就像您所做的那样。由于 EF Core 本质上不支持直接在数据库视图上建立关系,因为它们没有主键,因此您需要手动配置关系以确保其行为就像具有主键一样。

设置OnModelCreating(ModelBuilder modelBuilder)如下:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Palazzo>().HasKey(p => p.IdPalazzo);
    modelBuilder.Entity<Utente>()
        .HasOne(u => u.Palazzo) 
        .WithOne()
        .HasForeignKey<Utente>(u => u.IdPalazzo); 
}

将导航属性添加到

Utente
Palazzo
类:

public class Utente
{
      public int Id { get; set; } 
     public string Name { get; set; } = string.Empty;
     public int IdPalazzo     
     public List<Pratica>? Pratiche { get; set; }
     public Palazzo Palazzo { get; set; } // Navigation property
}

LINQ 查询:

var utentiWithPalazzo = dbContext.Utenti.Include(u => u.Palazzo).ToList();
© www.soinside.com 2019 - 2024. All rights reserved.