tags:

views:

162

answers:

1

I currently have 3 separate tables : Course, Category, and CourseCategory. CourseCategory is the connection only having the CourseID and CategoryId. I need a way in LINQ-to-SQL to add a Category property to Course objects that abstracts past the multiple tables. We need to change the application to only allow one category, but we don't want to change the database in case we need to switch it back later.

How can I add a property to Course that will get the first category in the CourseCategory table?

A: 

Just extend your Course entity with a new property. The following will expose the single category (not the CourseCatergory, but you can easily change that if you want the CourseCategory) assocciated with the course, return null if there is none and throw an exception if there is more than one.

public partial class Course
{
   public Category Category
   {
      get { return this.CourseCategories.SingleOrDefault().Category; }
   }
}

You could also add a setter to make the property writable.

UPDATE

You should even use Single() instead of SingleOrDefault() if having no category assocciated is not allowed, too.

Daniel Brückner
"the first category" - might want FirstOrDefault, and perhaps handle the null before calling .Category, but...
Marc Gravell
"only allow one category" - this implies SingleOrDefault() because finding more than one is a violation of the requirement "only one category". This should cause an exception - as SingleOrDefaullt() does - because there is probably a bug somewhere that caused a course to have more than one category.
Daniel Brückner
Using FirstOrDefault() hides this bug by simply returning the first category. It should even be Single() if having zero categories is disallowed, too.
Daniel Brückner
I need to use FirstOrDefault() because several of the items have multiple categories associated, which was allowed but we don't want to anymore, but I've been restricted from changing the database.
Stephan