Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I bind an Enum to a DbType of bit or int?

I am using Linq2Sql and want to bind an objects field (which is enum) to either a bit or a int type in the database. For example I want have a gender field in my model. I have already edited the DBML and changed the Type to point to my enum. I want to create Radio buttons (which I think I have figured out) for gender and dropdown lists for other areas using the same idea. My enum looks like this

public enum Gender
{
    Male,
    Female
}

Mapping between DbType 'int' and Type 'Project.Models.Gender' in Column 'Gender' of Type 'Candidate' is not supported.

Any ideas on how to do this mapping. Am I missing something on the enums.

like image 471
uriDium Avatar asked Apr 21 '10 19:04

uriDium


2 Answers

If you have an int enum like this:

public enum Gender
{
    Male = 0,
    Female
}

and int column in your database, the next mapping should work without problem.

<Column Name="Gender" Type="global::Project.Models.Gender" DbType="Int NOT NULL"
        CanBeNull="false" />

It is possible that global:: keyword is a key here. I had some problems with mapping integer data types to enums without it.

like image 109
Oleks Avatar answered Oct 10 '22 18:10

Oleks


I've found that whereas

Type="System.Boolean" DbType="bit" CanBeNull="true"

works out that the type should be a nullable[of boolean], for an enum I have to specify the type as the nullable type..

Type="WhatNextEnum?" DbType="int" CanBeNull="true"

If you don't you'll get the "DBML1005: Mapping between DbType 'int' and Type 'WhatNextEnum' ... is not supported." error

like image 38
Paul Nicklin Avatar answered Oct 10 '22 19:10

Paul Nicklin