【问题标题】:Is it possible to map stored procedures to entities in EF Core?是否可以将存储过程映射到 EF Core 中的实体?
【发布时间】:2021-04-27 13:12:36
【问题描述】:

EF Core 中的类似内容

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Student>()
                    .MapToStoredProcedures();
}

EF 6 具有自动创建存储过程的功能。我希望有类似于 EF Core 的东西或解决方法来实现代码优先的方法。

【问题讨论】:

  • 谢谢你,但我似乎无法在我的问题上找到解决方案。虽然我知道 EF Core 仍然没有这个功能。这就是为什么我希望看到解决方案,尽管存在限制。
  • 抱歉,我不知道有任何第三方实现。

标签: c# .net-core entity-framework-core ef-code-first relational-database


【解决方案1】:

我认为它可以帮助你。 您可以使用 T-SQL 命令创建自己的存储过程。如果你想尝试这种方式,你需要启用迁移并创建一个。 在你拥有一个之后,你需要创建一个继承你的 DbMigration 的部分类

public partial class SPAdder : DbMigration
{
    public override void Up()
    {
        CreateStoredProcedure(
            "dbo.ExampleSP",
            CreateStoredProcedure(
 "dbo.ExampleSP",
 p => new
 {
     Name = p.String(),
     LastName = p.String(),
     Hometowm = p.String(),
     StudentID = p.Int(),
 },
 body:
     @"
      if(exists(Select * from Student where StudentID = @StudentID))
          begin
              Update Student Set Name = @Name, LastName = @LastName, Hometown = @Hometown where StudentID =     @StudentID
          end
      else
          begin
              Insert Students(Name, LastName, Hometown) Values(@Name, @LastName, @Hometown)"
          end    
        );
         
    }
     
    public override void Down()
    {
        DropStoredProcedure("dbo.ExampleSP");
    }
}

【讨论】:

  • 谢谢,但我该如何执行呢?
  • 在你创建了自己的存储过程之后,你可以在你的主类中测试你的代码。 using (EntitiesContext context = new EntitiesContext()) { EmployeeMaster employee = new EmployeeMaster(); employee.Code = "A0001"; employee.Name = "Jignesh Trivedi"; employee.DepartmentId = 1; context.Employees.Add(employee); context.SaveChanges(); Console.ReadLine(); } 写完后,别忘了把你的日志扔掉,这样你就可以更清楚地查看了
  • 这个存储过程如何自动绑定到附加实体?
猜你喜欢
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多