使用ADO.net实体框架4枚举?我该怎么办呢? [英] Using ADO.net Entity Framework 4 with Enumerations? How do I do it?
问题描述
问题1:我玩弄EF4和我有一样的模型类:
Question 1: I am playing around with EF4 and I have a model class like :
public class Candidate {
public int Id {get;set;}
public string FullName {get;set;}
public Gender Sex {get;set;}
public EducationLevel HighestDegreeType {get;set;}
}
下面的性别与EducationLevel就像枚举:
Here Gender and EducationLevel are Enums like:
public enum Gender {Male,Female,Undisclosed}
public enum EducationLevel {HighSchool,Bachelors,Masters,Doctorate}
如何获得候选类和性别与EducationLevel与EF4工作,如果:
How do I get the Candidate Class and Gender and EducationLevel working with EF4 if:
- 在我做的模型首次开发
- 在我做的第一个数据库开发
编辑:涉及到对象上下文另一个问题here.
Moved question related to object context to another question here.
推荐答案
显然 INT< - >枚举
<一个href="http://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/7659feab-d348-4367-b2cd-0456b20262fe">won't在EF的初始版本将支持中4。我同意那些谁这样说很烂。
Apparently int <-> enum
won't be supported in the initial release of EF4. I agree with those who say this sucks.
我使用的是做铸件为我的属性
I am using a property that does the casting for me
public partial class MyEntity
{
public MyEnum HurrEnum {get{return (MyEnum)Hurr;} set{Hurr = (int)value;}}
}
它看起来并不那么糟糕,如果你的名字的东西正确(这意味着,所以它看起来并不愚蠢)。举例来说,我有一个储存在数据库中的一个原因原因code枚举,所以我有物业的理性与理性code版本。作品出来不够好,现在是这样。
It doesn't look so bad if you name stuff "correctly" (which means, so it doesn't look stupid). For instance, I have a ReasonCode enum that's stored as a Reason in the database, so I have Reason and ReasonCode versions of the property. Works out well enough, for now.
首先,我刚开始使用EF4所以我不亲近它是如何工作。我认为它类似于L2S但具有更好的实体支持。与盐,粮借此的
需要明确的是,这个属性是为了方便起见,我90%肯定,如果你尝试使用这个属性来查询数据库EF会产生不良反应。 EF不知道你的财产,不能用它来构造SQL。所以这样的:
To be clear, this property is for convenience and I'm 90% sure EF will react badly if you try to query the database using this property. EF doesn't know about your property and cannot use it to construct sql. So this:
var foo = from x in Db.Foos where x.HurrEnum == Hurr.Durr select x;
将可能无法按预期在哪里这样的:
will probably fail to behave as expected where this:
var foo = Db.Foos.Where(x=> x.HurrEnum == Hurr.Durr);
可能会导致整个FOOS表被带入内存中,然后进行解析。 此属性是为了方便起见,应使用的数据库已经被打后才如:!
// this is executed in the sql server
var foo = Db.Foos.Where(x=> x.Hurr == 1 || x.Hurr == 2).ToArray();
// this is then done in memory
var hurrFoos = foo.Where(x=> x.HurrEnum == Hurr.Durr);
如果你不明白这里的区别是,你在玩火。你需要学习如何EF / L2S除$ P $其中pts您code并将其转换成SQL语句。
If you don't understand the difference is here then you're playing with fire. You need to learn how EF/L2S interprets your code and converts it into sql statements.
这篇关于使用ADO.net实体框架4枚举?我该怎么办呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!