C# 使用autocomplete保存外键引用或创建新实体(如果是新项)
我有三个领域,分别是国家、部门和城市 我的数据库中有三个表,用户可以在其中键入。jQuery自动完成库允许用户键入名称并填写。我想让我的用户从现有的国家/部门/城市中进行选择,但如果他们无法选择,还可以让他们创建一个全新的项目C# 使用autocomplete保存外键引用或创建新实体(如果是新项),c#,asp.net-mvc-3,entity-framework-4,C#,Asp.net Mvc 3,Entity Framework 4,我有三个领域,分别是国家、部门和城市 我的数据库中有三个表,用户可以在其中键入。jQuery自动完成库允许用户键入名称并填写。我想让我的用户从现有的国家/部门/城市中进行选择,但如果他们无法选择,还可以让他们创建一个全新的项目 Country Department City ---------- ---------- --------- CountryId DepartmentId CityId Name Name Name
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();
}
首先,如果国家不存在,就会出现问题,我无法从部门代码中访问新创建的国家,因为它是在if Country==null条件中声明的
我觉得这有点复杂,我很感激任何关于如何清晰地编写这个需求的建议。我相信这并不像我的大脑告诉我的那么难。也许我对你的问题看得有点简单,或者不理解你的主要思想,但你应该能够将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,如果要在City If上使用,您可以在Department If内部使用相同的过程,如果我找到了,我会尽快发布我的答案。