Can a foreign key column be an Enum in Entity Framework 6 code first?

c# entity-framework-6 enums foreign-keys

Question

I am converting EF5 DB first into EF6 code first. in the old setup there are some FKs that are bytes. and in the application are mapped to enums with the underlining type of byte. this has been working wonderfully.

Going over to code first and EF6 I found claims that enums should "just work" and indeed that seems to be the case for regular columns. I can just go from this

public byte FavPersonality {get;set;}

to this:

public Personality FavPersonality {get;set;}

but when it comes to columns that are also foreign keys I get this error :

System.ArgumentException : The ResultType of the specified expression is not
compatible with the required type. The expression ResultType is 'Edm.Byte'
but the required type is 'Model.Personality'. 

Is this something that cannot be done with EF6 + Code first?

edit:

enum is defined as :byte

1
12
3/26/2015 4:10:09 PM

Popular Answer

I just ran into this same issue with my enum being a basic number enum, but this came up as the first result in the search by message. I had a subtype on my main object where the values were of a fixed set of values. But, there were also objects for those so we could write queries against them.

public class Foo {
    [Key]
    public int Id { get; set; }

    public BarEnum BarId { get; set; }

    [ForeignKey(nameof(BarId))]
    public Bar Bar { get; set; }
}

public class Bar {
    [Key]
    public int Id { get; set; }
}

public enum BarEnum {
    Type1,
    Type2
}

This configuration gave me the same error message as described in this question:

The ResultType of the specified expression is not compatible with the required type. The expression ResultType is 'BarEnum' but the required type is 'Edm.Int'.

The resolution for this was simple: Just change the Id of Bar to use the enum as well, and everything worked without a problem. This does make sense, as there are far more values possible for an int than there are for a BarEnum.

public class Bar {
    [Key]
    public BarEnum Id { get; set; }
}
7
8/17/2016 11:29:01 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow