I know this method is working well. However I reused most of the code and it looks ugly... It should be possible to remove the if else using delegate. Any thoughts?
public IHttpActionResult TimeDatawithUserandServer(string name, string group)
{
List<Model> res = new List<Model>();
//group 1 is Server type
if (group.Equals("1"))
{
var realName = name.Replace("-", ".");
IQueryable<Overalldata> UserData = db.Overalldatas.Where(x => x.Server.Equals(realName));
var groupedUserData = UserData.GroupBy(x => new {x.EventDate, x.User}).ToList();
res.AddRange(groupedUserData.Select(item => new Model()
{
Count = item.Count(),
Date = item.Key.EventDate.ToString("yyyy-MM-dd HH:mm:ss"),
Name = item.Key.User
}));
}
//group 2 is User type
else
{
IQueryable<Overalldata> Serverdata = db.Overalldatas.Where(x => x.User.Equals(name));
var groupServerData = Serverdata.GroupBy(x => new {x.EventDate, x.Server}).ToList();
res.AddRange(groupServerData.Select(item => new Model()
{
Count = item.Count(),
Date = item.Key.EventDate.ToString("yyyy-MM-dd HH:mm:ss"),
Name = item.Key.Server
}));
}
return Ok(res);
}
You could do it this way:
public IHttpActionResult TimeDatawithUserandServer(string name, string group)
{
var getName = group == "1"
? (Func<Overalldata, string>)(od => od.Server)
: (Func<Overalldata, string>)(od => od.User);
var realName = group == "1"
? name.Replace("-", ".")
: name;
var UserData = group == "1"
? db.Overalldatas.Where(x => x.Server == realName)
: db.Overalldatas.Where(x => x.User == realName);
var groupedData =
UserData
.ToArray()
.GroupBy(x => new { x.EventDate, Name = getName(x) })
.ToArray();
var res =
groupedData
.Select(item => new Model()
{
Count = item.Count(),
Date = item.Key.EventDate.ToString("yyyy-MM-dd HH:mm:ss"),
Name = item.Key.Name
})
.ToList();
return Ok(res);
}
Without Delegates
Your code can simply be refactored to following and relieved from repetition:
public IHttpActionResult TimeDatawithUserandServer(string name, string group)
{
List<Model> res = new List<Model>();
var groupedData = group.Equals("1") ? FetchServerData(name) : FetchUserData(name);
res.AddRange(groupedData.Select(item => new Model()
{
Count = item.Count(),
Date = item.Key.EventDate.ToString("yyyy-MM-dd HH:mm:ss"),
Name = item.Key.Server
}));
return Ok(res);
}
private GroupedDataType FetchServerData(string name)
{
var realName = name.Replace("-", ".");
var UserData = db.Overalldatas.Where(x => x.Server.Equals(realName));
return UserData.GroupBy(x => new {x.EventDate, x.User}).ToList();
}
private GroupedDataType FetchUserData(string name)
{
var Serverdata = db.Overalldatas.Where(x => x.User.Equals(name));
return Serverdata.GroupBy(x => new {x.EventDate, x.Server}).ToList();
}
Please replace the GroupedDataType with the appropriate type in the two methods above and in the code below.
With Delegates
Using Reflection we find the correct field (or property) and then compare the value as in the code below:
public IHttpActionResult TimeDatawithUserandServer(string name, string group)
{
List<Model> res = new List<Model>();
var groupedData = GetGroupedList(group, name);
res.AddRange(groupedData.Select(item => new Model()
{
Count = item.Count(),
Date = item.Key.EventDate.ToString("yyyy-MM-dd HH:mm:ss"),
Name = item.Key.Server
}));
return Ok(res);
}
private static IEnumerable<GroupedDataType> GetGroupedList(string group, string name)
{
var filteredList = db.Overalldatas.Where(dbData => Filter(dbData, group, name));
return filteredList.GroupBy(x => new {x.EventDate, x.User}).ToList();
}
private static readonly Func<ODType, string, string, bool> Filter = (ode, group, name) =>
{
var objType = overallDataElement.GetType();
var field = objType.GetMember(group)[0];
return (field != null)
&& ((FieldInfo) field).GetValue(ode).ToString().Equals(name);
};
ODType is Type of the elements in of Overalldatas list and ode is overalldata list's one single element.
I agreed with a comment made by lc who suggested running this through a code review.
There are some potential anti-patterns in your code
The group parameter is an example of control coupling
The control coupling is utilized via the if statement. For me, this is a clear sign that the method should be broken into separate methods.
I would also like to call attention to the Overalldatas collection. It's name is suspicious which leads to other questions including "Is this data object trying to do too much?". But I won't really touch and this as it's less relevant to your question and my answer.
That said, my answer is that you should have two methods, one for "Server Type" and one for "User Type". I realize this pushes that "group" check elsewhere, but that can be solved later and today the intent of your methods will be MUCH clearer.
public IHttpActionResult TimeDataByUserName(string userName)
{
List<Model> res = new List<Model>();
IQueryable<Overalldata> Serverdata = db.Overalldatas.Where(x => x.User.Equals(userName));
var groupServerData = Serverdata.GroupBy(x => new {x.EventDate, x.Server}).ToList();
res.AddRange(groupServerData.Select(item => new Model()
{
Count = item.Count(),
Date = item.Key.EventDate.ToString("yyyy-MM-dd HH:mm:ss"),
Name = item.Key.Server
}));
return Ok(res);
}
public IHttpActionResult TimeDataByServerName(string serverName)
{
List<Model> res = new List<Model>();
IQueryable<Overalldata> UserData = db.Overalldatas.Where(x => x.Server.Equals(serverName));
var groupedUserData = UserData.GroupBy(x => new {x.EventDate, x.User}).ToList();
res.AddRange(groupedUserData.Select(item => new Model()
{
Count = item.Count(),
Date = item.Key.EventDate.ToString("yyyy-MM-dd HH:mm:ss"),
Name = item.Key.User
}));
}
Related
I have method to add elements to list
Here is code
public static List<InputDevice> GetAudioInputDevices()
{
var inputs = new List<InputDevice>();
var enumerator = new MMDeviceEnumerator();
var devicesAudio = enumerator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
foreach (var device in devicesAudio)
{
inputs.Add(new InputDevice()
{
Name = device.FriendlyName,
Status = device.State.ToString(),
DeviceId = device.ID,
Identifier = device.FriendlyName.Replace(" ", "").ToUpper()
});
}
return inputs;
}
But sometimes I can have duplicates in Identifier
How I can return list without duplicates on return?
There's a few ways to accomplish this, you could just skip the Adding of the item if it's already in the list:
foreach (var device in devicesAudio)
{
string identifier = device.FriendlyName.Replace(" ", "").ToUpper();
if (inputs.Any(input => input.Identifier == identifier))
continue;
inputs.Add(new InputDevice()
{
Name = device.FriendlyName,
Status = device.State.ToString(),
DeviceId = device.ID,
Identifier = identifier
});
}
Or you could group the list by the identifier after the foreach, something like this:
inputs = inputs.GroupBy(i => i.Identifier)
.Select(i => new InputDevice()
{
Identifier = i.Key,
Status = i.First().Status,
DeviceId = i.First().DeviceId,
Name = i.First().Name
}).ToList();
It really depends on what you need to do with the duplicated ones.
Hope it helps!
To make it faster you can use HashSet (complexity of Contains for HashSet is o(1)) and ask on each loop whether there already is a specific identifier in inputs List.
public static List<InputDevice> GetAudioInputDevices()
{
var inputs = new List<InputDevice>();
var enumerator = new MMDeviceEnumerator();
var devicesAudio = enumerator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
var usedIdentifiers = new HashSet<string>();
foreach (var device in devicesAudio)
{
var identifier = device.FriendlyName.Replace(" ", "").ToUpper();
if (usedIdentifiers.Contains(identifier))
continue;
inputs.Add(new InputDevice()
{
Name = device.FriendlyName,
Status = device.State.ToString(),
DeviceId = device.ID,
Identifier = identifier
});
usedIdentifiers.Add(identifier);
}
return inputs;
}
The best way, I thing is this
public static List<InputDevice> GetAudioInputDevices()
{
var inputs = new List<InputDevice>();
var enumerator = new MMDeviceEnumerator();
var devicesAudio = enumerator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
inputs = devicesAudio.GroupBy(d => d.FriendlyName.Replace(" ", "").ToUpper()).Select(g => g.First())
.Select(d => new InputDevice()
{
Name = d.FriendlyName,
Status = d.State.ToString(),
DeviceId = d.ID,
Identifier = d.FriendlyName.Replace(" ", "").ToUpper()
}).ToList();
return inputs;
}
Check in website information about HashSet.
So I'm trying to use a DTO to reshape and return data, it's not working because I'm trying to push in an array of objects (as an IQueryable - which I don't think works) into the DTO, I'm also trying to push in dynamic data into one of the properties, as seen below in the 'hasCurrentUserLiked' property. I need to figure out How to change the objects from IQueryable, into actual objects so they can all be pushed into the DTO and the dynamic data can be worked out.
This is the code
public async Task<PagedList<UserPhoto>> GetSpecificFeed(UserParams userParams)
{
var user = _context.Users.FirstOrDefault(x => x.Username == userParams.u);
var userId = user.Id;
var photos = _context.UserPhotos;
var followerIds = _context.Follows.Where(x => x.FollowerId == userId).Select(x => x.FollowingId).ToList();
var feeds = _context.UserPhotos.Where(x => followerIds.Contains(x.UserId)).OrderByDescending(x => x.DateAdded);
// this doesn't work because 'feeds' is an IQueryable, not an object
var like = await hasCurrentUserLiked(user.Id, feeds.id);
// this has the same problem as above
var feedsToReturn = new FeedsForReturnDto
{
Id = feeds.Id,
PhotoUrl = feeds.photoUrl,
Username = feeds.Username,
Description = feeds.Description,
DateAdded = feeds.DateAdded,
IsImage = feeds.IsImage,
hasCurrentUserLiked = like,
Likes = feeds.Likes
}
return await PagedList<UserPhoto>.CreateAsync(feedsToReturn, userParams.PageNumber, userParams.PageSize);
}
I thought that I might be able to get each image.id in a similar way the 'followerIds' are worked out but I couldn't figure out how to get this to work
[EDIT]
As per Enas Osamas answer, I've changed the code to this and I've debugged it, feedsToReturn has the correct info, so it is doing what its supposed to do. The problem I'm having now is that I'm unable to return it as it can't convert the IEnumerable to an IQueryable. I tried adding an explicit cast but that didn't work, I also tried removing the PagedList, and replacing the type to but this didn't work. My is an IQueryable which might be the problem, I tried changing that to an IEnumerable but this would mess up the code in other places.
This is my new code (still returning 'feeds' instead of 'feedsToReturn', will change when it works)
public async Task<PagedList<UserPhoto>> GetSpecificFeed(UserParams userParams)
{
var user = _context.Users.FirstOrDefault(x => x.Username == userParams.u);
var userId = user.Id;
var photos = _context.UserPhotos;
var followerIds = _context.Follows.Where(x => x.FollowerId == userId).Select(x => x.FollowingId).ToList();
var feeds = _context.UserPhotos.Where(x => followerIds.Contains(x.UserId)).OrderByDescending(x => x.DateAdded);
var feedToReturn = feeds.AsEnumerable().Select(feed => new FeedsForReturnDto
{
Id = feed.Id,
PhotoUrl = feed.photoUrl,
Username = feed.Username,
Description = feed.Description,
DateAdded = feed.DateAdded,
IsImage = feed.IsImage,
hasCurrentUserLiked = hasCurrentUserLiked(user.Id, feed.Id),
Likes = feed.Likes
});
return await PagedList<UserPhoto>.CreateAsync(feeds, userParams.PageNumber, userParams.PageSize);
}
I also tried changing some of the types around and this is what I came up with. The problem here is this:
'System.Collections.Generic.IEnumerable<cartalk.api.Dtos.feeds.FeedsForReturnDto>' to 'System.Linq.IQueryable<System.Collections.IEnumerable>'
and this problem is with the 'feedsToReturn' in the last line
public async Task<PagedList<IEnumerable>> GetSpecificFeed(UserParams userParams)
{
var user = _context.Users.FirstOrDefault(x => x.Username == userParams.u);
var userId = user.Id;
var photos = _context.UserPhotos;
var followerIds = _context.Follows.Where(x => x.FollowerId == userId).Select(x => x.FollowingId).ToList();
var feeds = _context.UserPhotos.Where(x => followerIds.Contains(x.UserId)).OrderByDescending(x => x.DateAdded);
var feedToReturn = feeds.AsEnumerable().Select(feed => new FeedsForReturnDto
{
Id = feed.Id,
PhotoUrl = feed.photoUrl,
Username = feed.Username,
Description = feed.Description,
DateAdded = feed.DateAdded,
IsImage = feed.IsImage,
hasCurrentUserLiked = hasCurrentUserLiked(user.Id, feed.Id),
Likes = feed.Likes
});
return await PagedList<IEnumerable>.CreateAsync(feedToReturn, userParams.PageNumber, userParams.PageSize);
}
PagedList code
public static async Task<PagedList<T>> CreateAsync(IQueryable<T> source,
int pageNumber, int pageSize)
{
var count = await source.CountAsync();
var items = await source.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync();
return new PagedList<T>(items, count, pageNumber, pageSize);
}
[EDIT]
This is the hasCurrentUserLiked function, it works here
public bool checkCurrentUserLiked(int currentUserId, int imageId)
{
var doesCurrentUserLike = _context.PhotoLikes.Where(x => x.LikerId == currentUserId && x.ImageId == imageId);
var value = true;
if (doesCurrentUserLike == null)
{
value = false;
}
else
{
value = true;
}
return value;
}
You can try something like
feeds.AsEnumerable().Select(feed => new FeedsForReturnDto
{
Id = feed.Id,
PhotoUrl = feed.photoUrl,
Username = feed.Username,
Description = feed.Description,
DateAdded = feed.DateAdded,
IsImage = feed.IsImage,
hasCurrentUserLiked = hasCurrentUserLiked(user.Id, feed.id),
Likes = feed.Likes
});
This would return an IEnumerable containing all the feeds mapped to your DTO after being enumerated to avoid performing operations against the database
[EDIT]
you can maybe do a left join with the _context.PhotoLikes.
Like this
feeds.GroupJoin(_context.PhotoLikes,
f => new { Id = f.Id, UserId = user.Id },
p => new { Id = p.ImageId, UserId = p.LikerId },
(f, p) => new { feed = f, photoLike = p })
.SelectMany(f => f.photoLike.DefaultIfEmpty(),
(f, p) => new FeedsForReturnDto
{
Id = f.feed.Id,
PhotoUrl = f.feed.photoUrl,
Username = f.feed.Username,
Description = f.feed.Description,
DateAdded = f.feed.DateAdded,
IsImage = f.feed.IsImage,
hasCurrentUserLiked = p != null,
Likes = feed.Likes
});
Just note that in this part
f => new { Id = f.Id, UserId = user.Id },
p => new { Id = p.ImageId, UserId = p.LikerId },
the datatypes of properties in both objects must match or it won't compile
I've got an MVC ASP.Net app using Entity Framework v6.0 with an Employee's table.
We're using a Code First approach with the standard Create (CRUD) method that has a EF lookup for existing employee's and also an EF lookup for employee CreatedBy/ModifiedBy fields. Trying to create mocks for both (EF object stubs) fails.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "EmployeeID,TeamID,EmployeeADID,FirstName,MiddleName,LastName,EmailAddress,IsAdministrator,IsDeleted")] Employee employee)
{
if (ModelState.IsValid)
{
//Only unique employee IDs
var existingEmployee = db.Employees.FirstOrDefault(o => o.EmployeeADID == employee.EmployeeADID);
if(existingEmployee != null)
{
ViewBag.Error = "Employee ID must be unique, this employee (" + existingEmployee.FullName + ") already exists in the system.";
ViewBag.TeamID = new SelectList(db.Teams, "TeamID", "Name", employee.TeamID);
return View(existingEmployee);
}
SetAuditFields(employee);
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.TeamID = new SelectList(db.Teams, "TeamID", "Name", employee.TeamID);
return View(employee);
}
The problem is the SetAuditFields call and I need to mock db.Employees.AsNoTracking AsNoTracking for the Edit operation.
private void SetAuditFields(Employee employee, bool onlyModified = false)
{
char sep = '\\';
string pID = User.Identity.Name.Split(sep)[1].ToUpper();
var users = db.Employees.AsNoTracking().Where(c => c.EmployeeADID == pID || c.EmployeeID == employee.EmployeeID).ToList();
var currentUser = users.FirstOrDefault(u => u.EmployeeADID == pID);
if (onlyModified)
{
//Notice the AsNoTracking, when you set the db.Entry(object).State = EntityState.Modified; this query wont return anything as its in Modified Mode.
//var originalEmployee = db.Employees.AsNoTracking().FirstOrDefault(o => o.EmployeeID == employee.EmployeeID);
var originalEmployee = users.FirstOrDefault(o => o.EmployeeID == employee.EmployeeID);
employee.CreatedByID = originalEmployee.CreatedByID;
employee.CreatedDate = originalEmployee.CreatedDate;
employee.ModifiedByID = currentUser.EmployeeID;
employee.ModifiedDate = DateTime.Now;
}
else
{
employee.CreatedByID = currentUser.EmployeeID;
employee.CreatedDate = DateTime.Now;
employee.ModifiedByID = currentUser.EmployeeID;
employee.ModifiedDate = DateTime.Now;
}
}
So how do I mock db.Employees.AsNoTracking after initially mocking db.Employees?
The THESE TWO LINES COMMENTED OUT in the code below don't work and fail with:
"The member 'IQueryable.Provider' has not been implemented on type 'DbSet1Proxy' which inherits from 'DbSet1'
I also tried the mockContext.SetupSequence but I need to interchange between with AsNoTracking on and off. Surely there must be something I'm missing?
[TestMethod()]
public void Create_Submit_Test()
{
// Arrange
var employeeDoesntExist = new Employee { EmployeeID = 0, FirstName = "DoesntExist" };
var employeeAdmin = new Employee { EmployeeID=140, FirstName = "Bern", MiddleName = "", LastName = "O", EmployeeADID = "123", EmailAddress = "Bernard.O#a.com", TeamID = 1, IsDeleted = false, IsAdministrator = true };
var employeeNew = new Employee { FirstName = "Jez", MiddleName = "", LastName = "T", EmployeeADID = "321", EmailAddress = "Jeremy.Thompson#a.com", TeamID = 1, IsDeleted = false, IsAdministrator = true };
var mockContext = new Mock<ICTEntities>();
var employeeEmptyMock = base.GetQueryableMockDbSet(employeeDoesntExist);
var employeeAdminMock = base.GetQueryableMockDbSet(employeeAdmin);
//THESE TWO LINES COMMENTED OUT
//mockContext.Setup(m => m.Employees).Returns(employeeEmptyMock);
//mockContext.Setup(m => m.Employees.AsNoTracking()).Returns(employeeAdminMock);
mockContext.SetupSequence(x => x.Employees.AsNoTracking())
.Returns(employeeEmptyMock)
.Returns(employeeAdminMock);
//I dont want to save it to the Database, otherwise next time we run this the object will already exist, so I mock the call
mockContext.Setup(d => d.SaveChanges()).Returns(1);
var controller = new EmployeesController(mockContext.Object);
controller.ControllerContext = base.MockAccess().Object;
// Act
RedirectToRouteResult result = controller.Create(employeeNew) as RedirectToRouteResult;
// Assert
Assert.IsNotNull(result);
Assert.AreEqual("Index", result.RouteValues["Action"]);
}
Here is the GetQueryableMockDbSet method:
protected DbSet<T> GetQueryableMockDbSet<T>(params T[] sourceList) where T : class
{
var queryable = sourceList.AsQueryable();
var dbSet = new Mock<DbSet<T>>();
dbSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider);
dbSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression);
dbSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
dbSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(() => queryable.GetEnumerator());
return dbSet.Object;
}
I ended up creating a chain of mocks using a counter as per https://stackoverflow.com/a/14368486/495455
int callCounter = 1;
mockContext.Setup(m => m.Employees)
.Returns(() =>
{
if (callCounter == 1)
{
callCounter++;
return employeeToEditMockCU;
}
else
{
return employeeMockCU;
}
});
Mocking using a SetupSequence doesn't work for me after the first mock. The db.Employee becomes null after the first call. So I dont use a SetupSequence:
mockContext.SetupSequence(x => x.Employees)
.Returns(employeeToEditMockCU)
.Returns(employeeMockCU);
Also to get around the AsNoTracking() I ended up fetching the record to update and saving it without using EntityState.Modified:
EF Update using EntityState.Modified
How to update record using Entity Framework 6?
I'm hoping you can help me with an issue I'm having. I'm new to ElasticSearch and am currently trying to implement a log search method that's going to be filtering through large amounts of logs. Currently, I can make it filter based on selected log types and that works fine, but as soon as I add the second filter, it no longer returns any results.
The only difference between the two filters I've added so far is, one is an int array, the other is a string list as seen in the current code, I've also tried converting it to a string array but to no help.
[Route("logs/search")]
[HttpGet]
public ActionResult Index(int[] logTypes, int entityType, string entitySource)
{
using (var db = new mtaEntities())
{
var targetSources = new List<string>();
switch (entityType)
{
// Username/charactername
case 0:
var characters = db.characters.Where(i => i.charactername.ToLower().Replace("_", " ") == entitySource.ToLower()).ToList();
accounts user = null;
if (characters.Any())
{
var accountId = characters.FirstOrDefault().account;
if (accountId != null)
{
user = db.accounts.FirstOrDefault(i => i.id == accountId);
characters.AddRange(db.characters.Where(i => i.account == user.id));
}
}
else
{
user = db.accounts.FirstOrDefault(i => i.username.ToLower() == entitySource.ToLower());
if (user != null)
{
characters.AddRange(db.characters.Where(i => i.account == user.id).ToList());
}
}
if (user != null)
{
targetSources.Add("AC-" + user.id);
foreach (var item in characters)
{
targetSources.Add("CH-" + item.id);
}
}
break;
}
var filters = new List<Func<QueryContainerDescriptor<Log>, QueryContainer>>();
filters.Add(fq => fq.Terms(te => te.Field(fi => fi.LogType).Terms(logTypes)));
filters.Add(fq => fq.Terms(te => te.Field(fi => fi.SourceUser).Terms(targetSources)));
var searchDescriptor = new SearchDescriptor<Log>();
searchDescriptor.Query(q => q.Bool(b => b.Filter(filters)));
var query = ElasticClient.Search<Log>(searchDescriptor);
var results = query.Documents;
return View(new Logs
{
IndexLastRebuilt = db.settings.FirstOrDefault(i => i.name == "elasticIndexLastRebuilt").value,
LogResults = results.ToList(),
LogTypes = db.logtypes.ToList()
});
}
}
I have a linq query in my class. When I try to return one or another result the compiler throw a conversion type error related a "Anonymous Type" and I found no solution for it.
This is my code:
public static string VerificaExame(string desc)
{
var model = new ExameContext();
var res = model.DbExame.Where(exame => exame.Descricao.Trim() == desc.Trim()).Select(exame => new { Id = exame.Id, Codigo = exame.Codigo });
if (res == null)
res = model.DbExame.Where(exame => exame.Codigo.Trim() == desc.Trim()).Select(exame => new { Id = exame.Id, Descricao = exame.Descricao });
var ret = res.FirstOrDefault();
return JsonConvert.SerializeObject(ret);
}
And the error message:
Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
This error is referent to:
res = model.DbExame.Where(exame => exame.Codigo.Trim() == desc.Trim()).Select(exame => new { Id = exame.Id, Descricao = exame.Descricao });
Use a different variable (do not use res)
var res = model.DbExame.Where(exame => exame.Descricao.Trim() == desc.Trim()).Select(exame => new { Id = exame.Id, Codigo = exame.Codigo });
//^ Now res is of a specific type (ie: IEnumerable<Anonymous1>)
if (res == null)
var res2 = model.DbExame.Where(exame => exame.Codigo.Trim() == desc.Trim()).Select(exame => new { Id = exame.Id, Descricao = exame.Descricao });
//^ you cant affect res2 to res because they are of different type
if (res == null) res will never be null, may be you want if (!res.Any()) to see if res has items.
This is what you should do:
public static string VerificaExame(string desc)
{
var model = new ExameContext();
object res = (object)model.DbExame.Where(exame => exame.Descricao.Trim() == desc.Trim())
.Select(exame => new { Id = exame.Id, Codigo = exame.Codigo })
.FirstOrDefault()
??
(object)model.DbExame.Where(exame => exame.Codigo.Trim() == desc.Trim())
.Select(exame => new { Id = exame.Id, Descricao = exame.Descricao })
.FirstOrDefault();
if (res != null)
return JsonConvert.SerializeObject(res);
return JsonConvert.SerializeObject("");//Or throw an exception
}