EF5 does not create enum columns

2019-02-20 09:03发布

问题:

I have a model like this:

namespace Ad.NegCred.Data.Model {
    public enum DataKind {
        F, //Takibe alınıp henüz tahsil edilmeyen ferdi kredi bildirimi
        FA, //Aynı dönemde takibe alınan ve tahsil edilen ferdi kredi bildirimi
        FF, //daha önceki dönemlerde takibe alındığı bildirilmiş ferdi kredi tahsil bildirimi
        K, //Takibe alınıp henüz tahsil edilmeyan kredi kartı
        KA, //Aynı dönemde takibe alınan ve tahsil edilen kredi kartı
        KF //Daha önceki dönemlerde takibe alındığı bildirilmiş kredi kartı tahsil    bildirimi
    }

    public class Datum {
        [Key]
        public long Id { get; set; }
        public DataKind Kind { get; set; }
        [StringLength(25, MinimumLength = 2)]
        public string Name { get; set; }
    }
}

When database created by EF, all columns but the Kind column are created. Another enum column which is part of a complex type not shown here is not created as well.

Why does EF 5 behave like this? Is there a setting that I do not know about?

回答1:

You seem to be using EF5 and target .NET Framework 4. This won't work since System.Data.Entity.dll in .NET Framework 4 used by the EntityFrameork.dll cannot handle enums. You either need to move to EF5 and .NET Framework 4.5 or to EF6 where you can target .NET Framework 4 and use enums since EF6 doesn't depend on components shipped in .NET Framework anymore.



回答2:

Should work Ok, see MS EF site http://msdn.microsoft.com/en-us/data/hh859576

I use this and it works... and Enum is not created as TABLE on DB. The video shows you how to create ENUM on DB if that is required.

namespace XYZ.Core.Enum
{
public enum MasterEventType : int
{
    Undefined = 0,  
    Logon = 1,
    Logoff = 2,   
 }
}

namespace XYZ.Core.Model
{
public class MasterUserEventLog  
{
    // the rest is not relevant here....
    public MasterEventType EventType{ get; set; }       // what happened
}
{


回答3:

No table will be created by EF and that is by design. EF handles the enums internally. You don't have to worry about them. I have used Enum and they work fine. If you however want to explicitly store Enum in the database then I suggest creating rolling in your own code. However, you should note that making entities has the usual ceremony associated with it for enum as well.

You can visit the link http://msdn.microsoft.com/en-us/data/hh859576.aspx where it is clearly written that Ef does not create any table for the Enum.



回答4:

In EF 6 you will also find this behaviour occurs if you make your enum type derive from uint rather than the default int. e.g.

public enum LogStatus : uint

The above will not automatically generate a column in code first migrations so you have to drop the uint part:

public enum LogStatus

Which defaults to int basis and code-first is happy to create this column automatically.