FluentNHibernate: How to map database char to c# b

2019-06-13 03:52发布

问题:

I have set up my first project using FluentNHibernate. When I tried to get a list of records from a single table, I got an exception which says:

System.FormatException : String was not recognized as a valid Boolean.

The problem is that in the database table, there is a column called "flag" and its data type is char, but it only contains values of either '0' or '1'. So, I'd like to map it to type bool in my POCO:

public class Students
{
    public virtual int Id {get; private set;}
    public virtual string FirstName {get; set;}
    public virtual string LastName {get; set;}
    public virtual DateTime RegisterDate {get; set;}
    public virtual bool Flag {get; set;}
}

Now, in my Mappings.cs, how do I convert Flag to bool?

public class StudentMap : ClassMap<Students> {
    public StudentMap() {
        Id(x => x.Id);
        Map(x => x.FirstName).Column("first_name");
        Map(x => x.LastName).Column("last_name");
        Map(x => x.RegisterDate).Column("register_date");
        Map(x => x.Flag); // This won't work because 
                          // column "flag" is char, 
                          // whereas x.Flag is bool.

        }
    }

That's question 1.

Also, in the database, the table name is "students", but in my business model, I want to use the singular as Student, how can I do this? Right now, if I define my business class as Student, I will get an error which says something like the table "student" is not found.

The database is MySQL, if that matters.

Thanks for your hint.

回答1:

For part 1, use this on your app.config/nhibernate.config/whateverYourNHibernateConfigFile

<property name="query.substitutions">true 1, false 0</property>

Edit after comment:

If you're using fluent nhibernate, just uses its API, example

            var props = new Dictionary<string, string>();
            props.Add("query.substitutions","true 1, false 0");
            var sessionFactory = Fluently.Configure().BuildConfiguration().AddProperties(props);


回答2:

For part 1, in your configuration object, you need to set the query.substitutions property to true=1, false=0.

For part 2, there should be a Table("") method you can use to specify the table name in the StudentMap class.