标签 标签 标签

  • 一句话的事儿:

01.创建一个空的Migration文件

步骤1:Add-migration AddView

  1. public partial class AddView : Migration
  2. {
  3. protected override void Up(MigrationBuilder migrationBuilder)
  4. {
  5. migrationBuilder.Sql(
  6. @"CREATE VIEW [dbo].[PlayerClubView]
  7. AS SELECT p.Id AS PlayerId,p.Name AS PlayerName,c.Name AS ClubName
  8. FROM [dbo].[Players] AS p
  9. INNER JOIN [dbo].[Clubs] AS c
  10. ON p.ClubId=c.Id ");
  11. migrationBuilder.Sql(
  12. @"CREATE PROCEDURE [dbo].[RemoveGamePlayersProcedure]
  13. @playerId int=0
  14. AS
  15. DELETE FROM [dbo].[GamePlayer] WHERE [PlayerId]=@playerId
  16. Return 0 ");
  17. }
  18. protected override void Down(MigrationBuilder migrationBuilder)
  19. {
  20. migrationBuilder.Sql(
  21. @"DROP PROCEDURE [dbo].[RemoveGamePlayersProcedure] ");
  22. migrationBuilder.Sql(
  23. @"DROP VIEW [dbo].[PlayerClubView] ");
  24. }
  25. }

步骤2:Update-DataBase

image.png

步骤3:查询PlayerClubView

  • 在DataContex中注入 ```csharp modelBuilder.Entity() .HasNoKey() .ToView(“PlayerClubView”);

//无Primary Key public DbSet PlayerClubs { get; set; }

  1. - 查询
  2. ```csharp
  3. var playerClubs = context.PlayerClubs.ToList();
  • 查询结果

image.png

  • 增加筛选条件

    1. var playerClubs = context.PlayerClubs
    2. .Where(x => x.PlayerId > 1)
    3. .ToList();

    image.png

    02.原生SQL 语句

    image.png

  • 查询01:

    1. var leagues = context.Leagues.FromSqlRaw("SELECT *FROM [EFCoreDemo].[dbo].[Leagues]").ToList();

    image.png

  • 查询02:

    1. var clubs = context.Clubs
    2. .FromSqlRaw("SELECT *FROM [EFCoreDemo].[dbo].[Clubs]")
    3. .Include(x => x.League)
    4. .Include(x => x.Players)
    5. .ThenInclude(x => x.GamePlayers)
    6. .ToList();

    image.png

    03.原生SQL查询的要求

    image.png

  • 查询03

    1. var clubs = context.Clubs
    2. .FromSqlInterpolated($"SELECT *FROM dbo.Clubs WHERE Id>{0}")
    3. .ToList();

    image.png

  • 执行SP,前提是返回的字段必须与Entity一致匹配

    1. var data = context.Clubs
    2. .FromSqlInterpolated($"EXEC RemoveGamePlayersProcedure WHERE Id>{0}")
    3. .ToList();

    04.执行非查询类的SQL语句

    image.png

  • 执行存储过程

    1. var count = context.Database
    2. .ExecuteSqlRaw("EXEC dbo.RemoveGamePlayersProcedure {0}",2);
    3. count = context.Database
    4. .ExecuteSqlInterpolated($"EXEC dbo.RemoveGamePlayersProcedure {2}");

    image.png

    05.注册EF Core服务

    1. public DataContext(DbContextOptions<DataContext> options) : base(options)
    2. {
    3. }

  • 本文作者:GeekPower - Felix Sun
  • 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!