0

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.

aziz
  • 54
  • 2
  • 9
  • Possible duplicate of [How can I do a Union all in Entity Framework LINQ To Entities?](https://stackoverflow.com/questions/9828308/how-can-i-do-a-union-all-in-entity-framework-linq-to-entities) – avs099 Nov 08 '18 at 18:52

2 Answers2

4

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

Arion
  • 31,011
  • 10
  • 70
  • 88
0

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.

Steve Wilkes
  • 7,085
  • 3
  • 29
  • 32