我正在开发一个实体框架代码优先项目,我有多对多的关系:
服务提供商可以拥有多种服务类型,服务类型可以有许多服务提供商。
服务只有一种服务类型。
服务类型是一个枚举:
public enum ServiceTypeEnum
{
Ambulance = 1,
[Display(Name = "Cash Advance")]
CashAdvance = 2,
Hospitalization = 3,
Hotel = 4,
[Display(Name = "House Call")]
HouseCall = 5,
[Display(Name = "Medical Escort")]
MedicalEscort = 6,
Transfer = 7,
Repatriation = 8
}
服务提供商
public partial class ServiceProvider
{
public ServiceProvider()
{
ServiceTypes = new HashSet<ServiceTypeEnum>();
}
[Key]
public int ServiceProviderID { get; set; }
[Required]
[StringLength(100)]
public string Title { get; set; }
// This is OK for a single Service
//public virtual ServiceTypeEnum ServiceType { get; set; }
// I added this so that Service Providers can have multiple Service Types
public ICollection<ServiceTypeEnum> ServiceTypes { get; set; }
public IEnumerable<Service> Services { get; set; }
}
和 ServiceProviderViewModel :
public class ServiceProviderViewModel
{
public class CreateModel
{
public int ServiceProviderID { get; set; }
[Required]
[StringLength(100)]
[Display(Name = "Title")]
public string Title { get; set; }
public IEnumerable<KeyValuePair<string, int>> AllServiceTypes { get; set; }
public string[] SelectedServiceTypes { get; set; }
//public ServiceTypeEnum ServiceType { get; set; }
}
public class EditModel
{
...
}
}
}
最后 ServiceProviderController :
public ActionResult Create()
{
var _allServiceTypes = Enum.GetValues(typeof(ServiceTypeEnum))
.Cast<ServiceTypeEnum>()
.Select(t => new KeyValuePair<string, int>(t.ToString(), (int) t));
var viewModel = new ServiceProviderViewModel.CreateModel()
{
AllServiceTypes = _allServiceTypes
};
return View(viewModel);
}
[HttpPost]
public ActionResult Create(ServiceProviderViewModel.CreateModel viewModel)
{
if (ModelState.IsValid)
{
// This is OK for a single Service Type
//var serviceProvider = new ServiceProvider
//{
// Title = viewModel.Title,
// ServiceType = viewModel.ServiceType
//};
// For multiple Service Types
var serviceProvider = new ServiceProvider();
serviceProvider.Title = viewModel.Title;
for (int i = 0; i < viewModel.SelectedServiceTypes.Length; i++)
{
serviceProvider.ServiceTypes.Add((ServiceTypeEnum)Enum.Parse(typeof(ServiceTypeEnum), viewModel.SelectedServiceTypes[i].ToString()));
}
repository.InsertServiceProvider(serviceProvider);
repository.Save();
return RedirectToAction("Index");
}
return View(viewModel);
}
问题是;数据库中没有用于添加的服务类型的表或列。在调试时,我可以看到复选框的选定值被转换为相应的枚举并添加到serviceProvider.ServiceTypes
当我尝试获取服务类型时没有任何内容:
repository.ServiceProviders.ServiceTypes
我错过了什么?
答案 0 :(得分:2)
枚举是一个结构。只能保留类类型。实体框架正确地忽略了“关系”。您如何想象枚举将首先表示为数据库表?