aziz
aziz

Reputation: 54

Union in linq entity framework

I want to perform the following work in entity framework that can be done in sql very easily.

select 0 as employeeid, 'Select' as employeeName 
union

Select employeeid, employeeName from tblemployee where IsActive=true

help please.

Upvotes: 0

Views: 4302

Answers (2)

Steve Wilkes
Steve Wilkes

Reputation: 7135

Assuming that tblemployee is being mapped to an entity named Employee and your DbContext has a collection of Employees named Employees, you can do the following:

var allEmployeesPlusAnEmptyOne = 
    new[] { new Employee { EmployeeId = 0, Name = "Select" } }
    .Concat(dbContext.Employees.Where(e => e.IsActive));

...as mentioned by @Arion, you can use Union() if you want the Entity framework to remove duplicate objects, although I assume there wouldn't be any.

Upvotes: 0

Arion
Arion

Reputation: 31239

Maybe something like this:

With UNION

var t= Enumerable
         .Range(0,1)
         .Select (e =>
                    new{employeeid=0,employeeName="Select"})
       .Union(
          db.tblemployee
          .Select (u =>
                   new {employeeid=u.employeeid,employeeName=u.employeeName} ));

With UNION ALL

var t= Enumerable
         .Range(0,1)
         .Select (e =>
                    new{employeeid=0,employeeName="Select"})
       .Concat(
          db.tblemployee
          .Select (u =>
                   new {employeeid=u.employeeid,employeeName=u.employeeName} ));

Where db is the data context

Upvotes: 4

Related Questions