Enums with EF code-first - standard method to seeding DB and then using?

為{幸葍}努か 提交于 2019-11-27 07:47:22
VinnyG

Now supported : http://blogs.msdn.com/b/adonet/archive/2011/06/30/announcing-the-microsoft-entity-framework-june-2011-ctp.aspx

The Microsoft Entity Framework June 2011 CTP introduces both new runtime and design-time features. Here are some of the new runtime features:

  • The Enum data-type is now available in the Entity Framework. You can use either the Entity Designer within Visual Studio to model entities that have Enum properties, or use the Code First workflow to define entities that have Enum objects as properties. You can use your Enum property just like any other scalar property, such as in LINQ queries and updates...

There are several new features for the Entity Framework Designer within Visual Studio:

  • The Entity Designer now supports creation of Enums, spatial data-types and table-value functions from the designer surface...
Sergi Papaseit

Unfortunately, enums are not natively supported on EF 4.1. Here's one rather known article on how to deal with them: Faking enums on EF 4. It does, however, require a wrapper.

There's a simpler way to map enums in EF 4 however: just create an int property on your class to represent the int value of the enum. That's the property that EF should map, then have a "mini wrapper" property to allow you to use the enum.

public class Appointment 
{   
    public int ID { get; set; }
    public string Description { get; set; }

    // This property will be mapped
    public int DayOfWeekValue { get; set; }

    public DayOfWeek Day
    {
        get { return (DayOfWeek) DayOfWeekValue; }
        set { DayOfWeekValue = (int) value; }
    }
}

public enum DayOfWeek
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

On generating the database, EF will happily ignore any type it doesn't know how to map, but the int property will be mapped.

Note: This is taken directly from my answer to another enum and EF question: EF 4.1 Code First - map enum wrapper as complex type

I Wrote a post about that. You can use Code First Migrations to add your enum values to the database. Look here: http://linqto.net/blog/2012/10/entity-framework-code-first-and-enum-support/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!