在EFCore中执行Sql语句的方法为:FromSql与ExecuteSqlCommand;在EF6中的为SqlQuery与ExecuteSqlCommand,而FromSql和SqlQuery有很大区别,FromSql返回值为IQueryable,因此为延迟加载的,可以与Linq扩展方法配合使用,但是有不少的坑(EFCore版本为1.1.0),直接执行Sql语句的建议不要使用FromSql,但是EFCore中并没有提供SqlQuery方法,因此下面会贴出SqlQuery的实现代码供大家参考,以便在EFCore中能使用。

 

FromSql和ExecuteSqlCommand的使用

测试时使用了SqlServer2008和SqlServer Profiler进行Sql语句捕捉,EFCore的版本为1.1.0。

测试的Entity Model与DbContext

 1     public class MSSqlDBContext : DbContext
 2     {
 3         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
 4         {
 5             optionsBuilder.UseSqlServer(@"data source=localhost;initial catalog=TestDB;Integrated Security=True;");
 6         }
 7         public DbSet<Person> Person { get; set; }
 8         public DbSet<Address> Address { get; set; }
 9 }
10 
11     [Table(nameof(Person))]
12     public class Person
13     {
14         public int id { get; set; }
15         public string name { get; set; }
16         [Column(TypeName = "datetime")]
17         public DateTime? birthday { get; set; }
18         public int? addrid { get; set; }
19 }
20 
21     [Table(nameof(Address))]
22     public class Address
23     {
24         public int id { get; set; }
25         public string fullAddress { get; set; }
26         public double? lat { get; set; }
27         public double? lon { get; set; }
28     }
View Code

相关文章:

  • 2021-08-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-20
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-01-04
  • 2022-12-23
相关资源
相似解决方案