我有三个领域,分别是国家,部门和城市。
我的数据库中有三个用户可以键入的表。 jQuery自动完成库允许用户键入名称并填写。我想让我的用户从现有的国家/部门/城市中进行选择,但如果没有他们选择的话,也让他们创建一个全新的项目。
Country Department City
---------- ---------- ---------
CountryId DepartmentId CityId
Name Name Name
CountryId DepartmentId
我很难想象这个看似简单的过程。
这是我的代码:
EFRegistryCountryRepository registryCountryRepository = new EFRegistryCountryRepository();
var country = registryCountryRepository.FindAllRegistryCountries().SingleOrDefault(c => c.Name == model.Country);
if (country == null)
{
RegistryCountry newCountry = new RegistryCountry();
newCountry.Name = model.Country;
registryCountryRepository.AddRegistryCountry(newCountry);
registryCountryRepository.SaveChanges();
}
EFRegistryDepartmentRepository registryDepartmentRepository = new EFRegistryDepartmentRepository();
var department = registryDepartmentRepository.FindAllRegistryDepartments().SingleOrDefault(d => d.Name == model.Department && d.RegistryCountry.Name == model.Country);
if (department == null)
{
RegistryDepartment newDepartment = new RegistryDepartment();
newDepartment.RegistryCountryId = country.RegistryCountryId;
newDepartment.Name = model.Department;
registryDepartmentRepository.AddRegistryDepartment(newDepartment);
registryDepartmentRepository.SaveChanges();
}
EFRegistryCityRepository registryCityRepository = new EFRegistryCityRepository();
var city = registryCityRepository.FindAllRegistryCities().SingleOrDefault(d => d.Name == model.City);
if (city == null)
{
RegistryCity newCity = new RegistryCity();
newCity.RegistryDepartmentId = department.RegistryDepartmentId;
newCity.Name = model.City;
registryCityRepository.AddRegistryCities(newCity);
registryCityRepository.SaveChanges();
}
首先,如果Country不存在则存在问题,我无法从Department位代码访问新创建的Country,因为它是在if (country == null)
条件内声明的。
我觉得这有点令人费解,我很欣赏有关如何干净地编码此要求的任何建议。我确信它并不像我的大脑告诉我那么难。
答案 0 :(得分:0)
也许我正在简单地看一下你的问题,或者没有理解你的主要想法,但是你应该能够在保存项目后将if变量设置在if变量内部,EntityFramework将填充你的具有来自DB的标识值的Id字段, 所以例如你的代码的国家位可能是:
var country = registryCountryRepository.FindAllRegistryCountries().SingleOrDefault(c => c.Name == model.Country);
if (country == null)
{
RegistryCountry newCountry = new RegistryCountry();
newCountry.Name = model.Country;
registryCountryRepository.AddRegistryCountry(newCountry);
registryCountryRepository.SaveChanges();
**country = newCountry**
}
这将使您能够使用country对象来检查Department If上的CountryId,并且您可以在Department内使用相同的进程如果要在City上使用If