ADO.NET Data Services and NHibernate

Update: this is based on the old NHContrib LINQ provider; the current one, on the NHibernate core, does not have an NHibernateContext class. Also, ADO.NET Data Services are now called WCF Data Services. For additional information, please read this post.

With the arrival of the LINQ provider for NHibernate, NHibernate now supports ADO.NET Data Services. There are some restrictions, however:

  • Relations must be entities or simple collections of entities (Entity, IList, IList<T>), not sets (ISet<T>, HashSet<T>) or maps (IDictionary, IDictionary<K, V>, HashTable);
  • The ID property must be called either "ID", or end with "ID", for example, CustomerID, otherwise you must apply the DataServiceKeyAttribute to the primary key property;
  • The ID property must have a public setter as well as a public getter;
  • The ID property must be of a base type, such as int or string;
  • The collections to expose must be public properties of type IQueryable<T> or IOrderedQueryable<T>.

Here is an example:

public class Customer

{

    public virtual Int32 ID

    {

        get;

        set;

    }

    public virtual IList<Orders> Orders

    {

        get;

        private set;

    }

}

public class CustomersOrdersContext: NHibernateContext

{

    public CustomersOrdersContext()

    {

    }

    public CustomersOrdersContext(ISession session): base(session)

;nbsp;   {

    }

    public IOrderedQueryable<Orders> Orders

    {

        get

        {

            return(this.Session.Linq<Orders>();

        }

    }

    public IOrderedQueryable<Customers> Customers

    {

        get

        {

            return(this.Session.Linq<Customers>();

        }

    }

}

And, on the ADO.NET Data Services class:

[ServiceBehavior(IncludeExceptionDetailsInFaults = true)] 

public class CustomersOrdersDataService: DataService<CustomersOrdersContext>

{

    public static void InitializeService(DataServiceConfiguration config)

    {

       config.SetEntitySetAccessRule("*", EntitySetRights.All);
       config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
       config.DataServiceBehavior.AcceptCountRequests = true;
       config.DataServiceBehavior.AcceptProjectionRequests = true;
    }

}

The IncludeExceptionDetailInFaults helps debugging any exceptions that may occur, you should remove it in production code. Read this for additional information.

Bookmark and Share

                             

No Comments