我正在使用一个不能改变其结构的遗留数据库(至少现在还没有),它有这样的东西:
**Profile**:
profile_id
first_name
last_name
**OneBigLookupTableToRuleThemAll**:
lookup_id (PK)
category_id (PK) (refers to a recrod in a OneBigCategoryTableToRuleThemAll)
description (basically a label)
**ProfileProperties**:
property_key (PK GUID)
profile_id
lookup_id
UNIQUE constraint on profile_id, lookup_id
作为两个类别的例子:
Degrees (MD, PhD, MS, MPH, etc) -- cat_id 1, for example
Job Responsibilities (Statistician, Medical Doctor, Epidemiologist, etc) -- cat_id 2
因此,在查找表中,我们最终得到这样的内容:
lookup_id, cat_id, description
1 , 1 , MD
2 , 1 , PhD
3 , 1 , MS
4 , 1 , MPH
5 , 2 , Statistician
6 , 2 , Medical Doctor
7 , 2 , Epidemiologist
因此,在ProfileProperties表中,我们最终得到如下内容:
property_key, profile_id, lookup_id
some guid , 1 , 1 -- MD degree
some guid , 1 , 4 -- MPH degree
some guid , 1 , 6 -- Medical Doctor
我想要一个这样的实体:
public class Profile {
public int ProfileId { get; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<JobResponsibility> JobResponsibilities { get; set; }
public ICollection<Degree> Degrees { get; set; }
}
public class JobResponsibility {
public int Id { get; set; }
public string Description { get; set; }
}
public class Degree {
public int Id { get; set; }
public string Description { get; set; }
}
——实际上,在Id的setter中,我想将值约束为数据库中的实际值之一,尽管我不确定我会完全支持enum类型(我知道代码首先不支持)
我相信一个实体框架映射场景应该能够处理这个,但我有麻烦弄清楚我需要做什么才能让它工作。
谁有什么建议或资源,我可以阅读这种情况?我认为它最终会非常基本,但我是EF的新手。
谢谢你,Josh
我不认为任何实体框架映射(特别是如果我们谈论流畅/代码优先)能够直接映射-我刚刚测试了继承方法,它没有工作。EF很大程度上依赖于数据库的设计方式。在您的情况下,您很可能会以这样的内容结束:
public class Profile
{
public int ProfileId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<ProfileProperty> Properties { get; set; }
}
public class ProfileProperty
{
public Guid PropertyId { get; set; }
public int ProfileId { get; set; }
public int PropertyId { get; set; }
public virtual Profile Profile { get; set; }
public virtual Property Property { get; set; }
}
public class Property
{
public int LookupId { get; set; }
public int CategoryId { get; set; }
public string Description { get; set; }
}
现在,如果你想有像度这样的属性,你必须添加非映射属性,如:
public IEnumerable<Property> Degrees
{
get { return Properties.Where(p => p.Property.CategoryId == 1)
.Select(p => p.Property);
}
只能读取而不能修改属性。对于修改,您将需要更复杂的逻辑来构建真正的Properties
集合中的正确结构。
即使计划在。net 4.5中支持枚举也无法解决这个问题。枚举将只支持将单个整列表示为枚举,但在您的情况下,您需要将多对多关系分解为多个枚举。