Question

I'm new to Telerik OpenAccess ORM and using for MVC project with database first approach. I went through this tutorial video on their site about Models: http://tv.telerik.com/watch/orm/building-a-mvc-3-application-database-first-with-openaccess-creating-model?seriesID=1529

I'm curious to know how can I extend domain class & query database from the Modal? For example I have a generated "Person" class & I'm extending it with the following class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCApplication
{
    public partial class Person
    {
        public string PersonName
        {
            get
            {
                return this.FirstName + " " + this.LastName;
            }
        }
    }
}

This is very similar to the example shown in video above. I'm curious if I can retrive all records from Person table or a collection of Person object where a certain criteria is meet? How will my "return" query be? I do not have dbContext available in this extended Model class :(

public List<Person> GetAllPeople()
{
// return List here
}

public List<Person> GetAllPeopleFromLocationA(int locationID)
{
//return List here
}
Was it helpful?

Solution

In general the domain classes are not meant to query the database and I suggest you to add the GetAllPeople and GetAllPeopleFromLocationA methods in a partial class of your domain context like below:

public List<Person> GetAllPeople()
{
    return this.People.ToList();
}

public List<Person> GetAllPeopleFromLocationA(int locationID)
{
    return this.People.Where(p => p.LocationID == locationID).ToList();
}

then you could use those methods like:

using (YourContextName context = new YourContextName())
{
    foreach (Person person in context.GetAllPeople())
    {
        // you could access your custom person.PersonName property here
    }

    foreach (Person person in context.GetAllPeopleFromLocationA(someLocationID))
    {
        // you could access your custom person.PersonName property here
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top