将 ADO.net Entity Framework 4 与枚举一起使用?我该怎么做?

编程入门 行业动态 更新时间:2024-10-28 22:26:39
本文介绍了将 ADO Entity Framework 4 与枚举一起使用?我该怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

Here Gender and EducationLevel are Enums like:

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

How do I get the Candidate Class and Gender and EducationLevel working with EF4 if:

  • I do model first development
  • I do db first development

Edit: Moved question related to object context to another question here.

解决方案

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.

更多推荐

将 ADO.net Entity Framework 4 与枚举一起使用?我该怎么做?

本文发布于:2023-11-14 16:23:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587944.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:怎么做   我该   net   ADO   Framework

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!