I have a data model like this in SQL Server:
table Note
- varchar NoteText
- tinyint PriorityLevel
In my code, Entity Framework turns it into a class like:
class Note
- string NoteText
- byte PriorityLevel
Also in code I have a PriorityLevel en开发者_高级运维um which makes my code more readable:
public enum PriorityEnum : byte
{
NORMAL = 10,
IMPORTANT = 20,
URGENT = 30
}
So, I would like to use that enum directly with my Note objects, like myNote.PriorityLevel = PriorityEnum.NORMAL
rather than having to cast all the time like myNote.PriorityLevel = (byte)PriorityEnum.NORMAL
.
I already have a solution via use of Partial
class declaration, but I wind up with two similarly-named properties that map to the underlying PriorityLevel, which is messy:
class Note
- string NoteText
- byte PriorityLevel
- PriorityEnum PriorityLevelEnum (gets/sets PriorityLevel)
Naturally I would like my EF class to be defined simply like:
class Note
- string NoteText
- PriorityEnum PriorityLevel
FYI I'm using POCO generation of my EF entity classes, so I figure the solution may involve a change to the T4 templates that generate them, but I'm concerned I'm missing out on something simple. I think there may be a solution by changing field definitions in the EDMX designer but I worry that they might be overwritten next time I update the EDMX from the database definition.
With current version of entity framework you will always need both properties because EF is not able to convert enums automatically and use them in mapping (that will change in future version).
So your entity defined in EDMX must have byte property and your partial class must expose second property using the enum and make conversion to byte internally within getter and setter. What you can do is reduce accessibility of your former mapped property. The disadvantage of this scenario is that Linq-to-entities queries cannot use your enum property - they must use original byte property and code defining the queries must have access to that property.
Modifying template to create enum properties for you would not be so easy because the template needs some information to differ between standard byte property and enum like property. You can involve some naming convention to infer enums but if you really like generic solution you must modify EDMX manually and use structural annotations to tell T4 template what enum type should be used for a related property.
精彩评论