关于Entity Framework 4中的实体、角色和接口的问题
我是一位经验丰富的 .NET 开发人员,但对 EF 很陌生 - 所以请耐心等待。我将用一个大学申请的例子来说明我的问题。我有这些用户角色:
讲师、学生、管理员。
在我的代码中,我设想将这些实体作为不同的类来使用,例如讲师教授一组学生。并使用“is Student”、“TypeOf”等。
这些实体中的每一个都共享许多通用属性/方法,例如,它们都可以登录到系统并执行与其角色相关的操作。
在 EF 设计器中,我可以创建一个基本实体 Person(或 User...),并让讲师、学生和管理员都继承自该实体。
我遇到的困难是讲师可以成为管理员 - 事实上有时学生也可以成为讲师。
如果我要添加其他实体,例如 Employee 和 Warden,那么这会成为一个更大的问题。
我大概可以使用接口,这样人们就可以实现 ILecturer 和 IStudent,但是我不知道这如何适合 EF。
如果可能的话,我想在 EF 设计器中工作,并且我正在模型优先工作(用 C# 编码)。
因此,任何帮助和建议/样品都将非常受欢迎和感激。
谢谢
I am an experienced .NET developer but new to EF - so please bear with me. I will use an example of a college application to illustrate my problem. I have these user roles:
Lecturer, Student, Administrator.
In my code I envisage working with these entities as distinct classes so e.g. a Lecturer teaches a collection of Students. And work with 'is Student' 'TypeOf' etc.
Each of these entities share lots of common properties/methods e.g. they can all log onto the system and do stuff related to their role.
In EF designer I can create a base entity Person (or User...) and have Lecturer, Student and Administrator all inherit from that.
The difficulty I have is that a Lecturer can be an Administrator - and in fact on occasion a Student can be a Lecturer.
If I were to add other entities such as Employee and Warden then this gets even more of an issue.
I could presumably work with Interfaces so a person could implement ILecturer and IStudent, however I do not see how this fits within EF.
I would like to work within the EF designer if possible and I'm working model-first (coding in C#).
So any help and advice/samples would be very welcome and much appreciated.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要让
Student
和Lecturer
继承自Person
。正如你所说,如果“鲍勃”既是学生又是讲师怎么办?这种情况在真正的大学里经常发生。您自己说得最好:这些是角色,而不是类型。一个人可以扮演多种角色。根据经验,当不是绝对必要时(几乎从来没有),请避免在 O/R 映射中继承。就像编码时一样,优先考虑组合而不是继承。
因此,您可以为每个
Person
提供一个属性Roles
,它是Role
的0..*集合。然后,要获取学生列表,您可以执行以下操作:或者,您可以拥有一个相关的
Student
类型,并且Person
之间的关系为 0..1和学生
;这将允许您为学生添加额外的数据,例如:Don't make
Student
andLecturer
inherit fromPerson
. As you say, what if "Bob" was both a student and a lecturer? This happens all the time in real colleges. You said it best yourself: These are roles, not types. A person can have many roles.As a rule of thumb, avoid inheritance in O/R mapping when it's not strictly necessary (which is almost never). Just as when coding, favor composition over inheritance.
So you could give each
Person
a propertyRoles
which is a 0..* collection ofRole
s. Then to get a list of students, you can do:Or you could have a related
Student
type with a 0..1 relationship betweenPerson
andStudent
; this would allow you to add additional data for the student, e.g.: