Реализация связи один ко многим в Entity Framework и domain driven design
У меня есть три сущности: Region
, Country
, City
.
City
является корневым агрегатом.
Поля Title
у каждой сущности являются уникальными.
public sealed class Country
{
public Country(Guid id, string title)
{
Id = id;
Title = title;
}
public Guid Id { get; private set; }
public string Title { get; private set; }
}
public sealed class Region
{
public Region(Guid id, string title, Country country)
{
Id = id;
Title = title;
Country = country;
CountryId = country.Id;
}
private Region()
{
}
public Guid Id { get; private set; }
public string Title { get; private set; }
public Guid CountryId { get; private set; }
public Country Country { get; private set; }
}
public sealed class City
{
public City(Guid id, string title, Region region)
{
Id = id;
Title = title;
Region = region;
RegionId = region.Id;
}
private City()
{
}
public Guid Id { get; private set; }
public string Title { get; private set; }
public Guid RegionId { get; private set; }
public Region Region { get; private set; }
}
Вопрос такой: как правильно сделать метод добавления сущности City
в базу данных?
Есть репозиторий городов CityRepository
, там метод AddAsync
. В нем я ищу в базе регионы и страны в базе и создаю по новой City
, чтобы была реализована связь один-ко-многим.
public async Task AddAsync(City city)
{
var country = await _context.Countries.FirstOrDefaultAsync(x => x.Title == city.Region.Country.Title);
if (country is null)
{
country = new Country(Guid.NewGuid(), city.Region.Country.Title);
}
var region = await _context.Regions.FirstOrDefaultAsync(x => x.Title == city.Region.Title);
if (region is null)
{
region = new Region(Guid.NewGuid(), city.Region.Title, country);
}
var existCity = await _context.Cities.FirstOrDefaultAsync(x => x.Title == city.Title);
if (existCity is null)
{
existCity = new City(Guid.NewGuid(), city.Title, region);
}
await _context.Cities.AddAsync(existCity);
await _context.SaveChangesAsync();
}
Есть другая реализация этого метода. В другой реализации как параметр метода передаются названия города, региона и страны.
public async Task AddAsync(string cityTitle, string regionTitle, string countryTitle)
{
var country = await _context.Countries.FirstOrDefaultAsync(x => x.Title == countryTitle);
if (country is null)
{
country = new Country(Guid.NewGuid(), countryTitle);
}
var region = await _context.Regions.FirstOrDefaultAsync(x => x.Title == regionTitle);
if (region is null)
{
region = new Region(Guid.NewGuid(), regionTitle, country);
}
var city = await _context.Cities.FirstOrDefaultAsync(x => x.Title == cityTitle);
if (city is null)
{
city = new City(Guid.NewGuid(), cityTitle, region);
}
await _context.Cities.AddAsync(city);
await _context.SaveChangesAsync();
}
Есть какие то другие варианты? Просто такие решения очень громоздкие. Заранее всем спасибо за помощь.
Источник: Stack Overflow на русском