views:

114

answers:

1

Hi

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.

+1  A: 

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.

Alex
I have also added the global:: from another post and the build problems have gone away and now it is saving into the database correctly. My next problem is when I do a linq select. It is giving me invalid cast exceptions. I am not sure if it is related to the enum I have used. Does the DbType have to be non null?
uriDium
@uriDium: I didn't use nullable enumerations with LINQ, but suppose it should work: set DbType="Int" and CanBeNull="true".
Alex
Okay, I tried everything again. Maybe something got confused. I redragged the table into the designer, changed the type again and presto everything works. I thought the global:: bus was meant to have been sorted out. Guess not. Thanks
uriDium
Alex, do you have to modify the DBML by hand to do this? What happens when someone refreshes the object in the DBML designer? Does your change get wiped out?
Robert Harvey
@Robert Harvey: yes, most of the changes to model I've made by hand on my last project. The thing is: the project is expanding, alongside with project the data layer is expanding too. I have to add new fields to the database quite often. For me it is not too comfortable doing this using designer. One more thing: the designer is quite buggy (I tried to add 2 tables some time ago but the try was unsuccessful). But happily, I'm the only one person who working with the data/BLL.
Alex
The designer is stable if you refresh the Server Explorer, and save before *and* after adding the tables, IME.
Robert Harvey