EF CORE 如何直接执行SQL并转化为指定的泛型对象我不想把对象定义在DbContext里
可以使用 EF Core 提供的 FromSqlRaw 方法执行 SQL 并将结果转换为指定的泛型对象。下面是一个示例:
public class MyEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
public class MyDbContext : DbContext
{
public DbSet<MyEntity> MyEntities { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("connection string");
}
}
public class MyRepository
{
private readonly MyDbContext dbContext;
public MyRepository(MyDbContext dbContext)
{
this.dbContext = dbContext;
}
public List<MyEntity> GetMyEntities()
{
var sql = "SELECT * FROM MyEntities";
return dbContext.MyEntities.FromSqlRaw(sql).ToList();
}
}
在上面的示例中,MyEntity 是定义在 DbContext 外部的实体类,而 GetMyEntities 方法直接执行 SQL 并将结果转换为 MyEntity 对象的列表。注意,要使用 FromSqlRaw 方法,需要在 DbContext 的 OnModelCreating 方法中将实体类配置为无操作(no operation):
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<MyEntity>().HasNoKey().ToView(null);
}
``
原文地址: http://www.cveoy.top/t/topic/czLq 著作权归作者所有。请勿转载和采集!