8

问题 1:我正在玩 EF4,我有一个模型类,例如:

public class Candidate {

public int Id {get;set;}
public string FullName {get;set;}
public Gender Sex {get;set;}
public EducationLevel HighestDegreeType {get;set;}
}

这里的 Gender 和 EducationLevel 是枚举,例如:

public enum Gender {Male,Female,Undisclosed}
public enum EducationLevel {HighSchool,Bachelors,Masters,Doctorate}

在以下情况下,我如何让候选类别以及性别和教育级别与 EF4 一起使用:

  • 我先做模型开发
  • 我做db第一个开发

编辑:将与对象上下文相关的问题移至此处的另一个问题。

4

1 回答 1

16

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;}}
}

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.


First, I'm just starting to use EF4 so I'm not intimate with how it works. I assume its similar to L2S but with better entity support. Take this with a grain of salt.

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);

probably will result in the entire Foos table being brought into memory and then parsed. This property is for convenience and should be used only after the database has been hit! Such as:

 // 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);

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.

于 2010-01-14T16:31:29.473 回答