.NET Core 中是否类似于 Ruby on Rails 中的 ActiveRecord?

Anu*_*bix 5 c# ruby activerecord ruby-on-rails asp.net-core

我正在从 Rails 切换到 .NET Core,但我真正怀念的是 ActiveRecord ORM。在模型中,您只需定义关系:

#Town Model
class Town < ApplicationRecord
  belongs_to :country
end

#Country Model
class Country < ApplicationRecord
  has_many :towns
end
Run Code Online (Sandbox Code Playgroud)

然后您可以简单地获取特定国家所有城镇的列表:

@country = Country.find(params[:id])
@towns = @country.towns
Run Code Online (Sandbox Code Playgroud)

这非常清楚,尤其是在您通过 id 链接多个模型的情况下。在 .Net Core 中,我通常会得到这样的结果:

Task<List<Town>> towns = await _context.Towns.Where(x => x.CountryId == countryId).ToListAsync();
Run Code Online (Sandbox Code Playgroud)

这仍然可以接受,但只是因为只有模型 - 模型关系。

假设我们想要在 Rails 中获取所选城镇的大陆:

@town = Town.find(params[:id])
@continent = @town.country.continent
Run Code Online (Sandbox Code Playgroud)

在.NET Core中,现在我必须使用连接,最终结果将非常复杂,这里很容易犯错误(而且情况并不复杂)。图像具有非常复杂的 SQL 查询,LINQ 对您帮助不大,而且您非常接近编写纯 SQL。

这就是为什么我问,.NET Core 中是否有类似于 Rails 中非常方便的 ActiveRecord ORM 的东西。

感谢您的回复和时间。

Gur*_*ron 2

EF 支持开箱即用的导航属性,因此在简单的情况下您不需要联接。如果需要,您也可以使用延迟加载。例如,请参阅此处此处此处的更多信息。

在您的情况下,如果您在实体之间正确设置了关系,则可以翻译

@country = Country.find(params[:id])
@towns = @country.towns
Run Code Online (Sandbox Code Playgroud)

进入:

var country = await _context.Country.Include(c => c.Towns).FindAsync(countryId); 
// or await _context.Country.Include(c => c.Towns).FirstAsync(c => c.Id == countryId) 
var towns = country.Towns;
Run Code Online (Sandbox Code Playgroud)

或者启用延迟加载:

var country = await _context.Country.FindAsync(countryId); 
var towns = country.Towns;
Run Code Online (Sandbox Code Playgroud)

第二个片段:

@town = Town.find(params[:id])
@continent = @town.country.continent
Run Code Online (Sandbox Code Playgroud)

可以翻译为:

var town = await _context.Town
     .Include(t => t.Country)
     .ThenInclude(c => c.Continent)
     .FindAsync(TownId); 
var country = town.Country.Continent;
Run Code Online (Sandbox Code Playgroud)

  • @Anubix 它将生成一个查询,您可以在 EF core 中启用日志记录,然后您将能够看到查询。 (2认同)