Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database

Fluent NHibernate - Working with Database Views

5.00/5 (1 vote)
5 Mar 2011CPOL 33.6K  
Fluent NHibernate - Working with Database Views

So, it turns out you can work with Views with Fluent NHibernate just as you were to work with tables. All you need to do is define your entity with the name of the view, instead of the table name.

For example:

C#
public class UserEntity
{
    public virtual int UserId { get; private set; }
    public virtual String FirstName { get; set; }
    public virtual String LastName { get; set; }
    public virtual int UserStatusId { get; set; }
    public virtual String UserStatus { get; set; }
}

public class UserEntityMap : ClassMap<UserEntity>
{
    public UserEntityMap()
    {
        Table("view_Users");  // this is mapped to a view, and not a table

        Id(x => x.UserId);
        Map(x => x.FirstName);
        Map(x => x.LastName);
        Map(x => x.UserStatusId);
        Map(x => x.UserStatus);  // This field is from another table
                                 // it is from a separate code table 
			// that describes the different statuses in the system
    }
}

An exception is thrown, when trying to update the entity that is mapped to a view. The problem is actually because when working with a view, you cannot execute an update query that updates rows on different tables. It will only work when updating rows on one table in the view.

In order to get around this, we need to tell the mapping that some properties aren't to be updated. This will solve the problem.

For example:

C#
public class UserEntityMap : ClassMap<UserEntity>
{
    public UserEntityMap()
    {
        Table("view_Users");  // this is mapped to a view, and not a table

        Id(x => x.UserId);
        Map(x => x.FirstName);
        Map(x => x.LastName);
        Map(x => x.UserStatusId);
        Map(x => x.UserStatus).Not.Update();
    }
}

Marking the mapping class with '.Not.Update()' tells FNH to return false on the update property of this field.

Likewise, we can also mark an attribute as '.Not.Insert()' and then the field will only be updatable, or mark a field as '.ReadOnly()' and the field will act as if it has a private set.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)