I have following code for updating user's column
public void UpdateLastModifiedDate(string username)
{
using (AppEntities db = new AppEntities())
{
var result = from u in db.Users where (u.UserName == username) select u;
if (result.Count() != 0)
{
var dbuser = result.First();
dbuser.LastModifiedDate = DateTime.Now;
db.SaveChanges();
}
}
}
I have other's 2 function of almost same of above function for UpdateLastLogOutDate, UpdateLastLoginDate. So, I decided to define single function for all to update Last Date like:
public void UpdateLastDate(string username, string ColumnName);
Here, I can not put ColumnName variable like this:
dbuser.ColumnName = DateTime.Now;
Is there any other way to do this using LINQ
You could define the method like this:
public void Update(string username, Action<User> action)
{
using (AppEntities db = new AppEntities())
{
var result = from u in db.Users where (u.UserName == username) select u;
if (result.Count() != 0)
{
var dbuser = result.First();
action(dbuser);
db.SaveChanges();
}
}
}
And now there could be different usages of this method:
Update("john", user => user.LastModifiedDate = DateTime.Now);
Update("smith", user => user.UpdateLastLogOutDate = DateTime.Now);
Update("admin", user =>
{
user.LastModifiedDate = DateTime.Now;
user.UpdateLastLogOutDate = DateTime.Now;
});
But if the expression is not known at compile time you may take a look at dynamic LINQ.
You could write your code this way also by sending an instance of your entity as parameter:
public void UpdateLastModifiedDate(Entityclassname ent) //[like if table name is item then Entityclassname should be items etc..]
{
using (AppEntities db = new AppEntities())
{
var result = from u in db.Users where (u.UserName == ent.username) select u;
if (result.Count() != 0)
{
var dbuser = result.First();
dbuser.LastModifiedDate = DateTime.Now;
dbuser.UpdateLastLogOutDate=ent.UpdateLastLogOutDate ;
db.SaveChanges();
}
}
}
Related
Thanks in advance. I can get required output when using var but i want to get required output by using Distinct in List<>.
InventoryDetails.cs
public class InventoryDetails
{
public int? PersonalInventoryGroupId { get; set; }
public int? PersonalInventoryBinId { get; set; }
}
InventoryController.cs
[HttpGet("GetInventory")]
public IActionResult GetInventory(int id)
{
//Below code will return distinct record
var inventory = (from i in _context.TempTbl
where i.TempId == id
select new
{
PersonalInventoryBinId = i.PersonalInventoryBinId,
PersonalInventoryGroupId = i.PersonalInventoryGroupId,
}).ToList().Distinct().ToList();
//Below code is not doing distinct
List<InventoryDetails> inventory = (from i in _context.TempTbl
where i.TempId == id
select new InventoryDetails
{
PersonalInventoryBinId = i.PersonalInventoryBinId,
PersonalInventoryGroupId = i.PersonalInventoryGroupId,
}).ToList().Distinct().ToList();
}
If i use var as return type, then i am able to get distinct records. Could some one assist it.
Please try like this it may help.
IList<InventoryDetails> inventory = _context.InventoryDetails.Where(x=>x.TempId == id).GroupBy(p => new {p.PersonalInventoryGroupId, p.PersonalInventoryBinId } )
.Select(g => g.First())
.ToList();
You need to override Equals and GetHashCode.
First, let's see the AnonymousType vs InventoryDetails
var AnonymousTypeObj1 = new { PersonalInventoryGroupId = 1, PersonalInventoryBinId = 1 };
var AnonymousTypeObj2 = new { PersonalInventoryGroupId = 1, PersonalInventoryBinId = 1 };
Console.WriteLine(AnonymousTypeObj1.Equals(AnonymousTypeObj2)); // True
var InventoryDetailsObj1 = new InventoryDetails { PersonalInventoryBinId = 1, PersonalInventoryGroupId = 1 };
var InvertoryDetailsObj2 = new InventoryDetails { PersonalInventoryBinId = 1, PersonalInventoryGroupId = 1 };
Console.WriteLine(InventoryDetailsObj1.Equals(InvertoryDetailsObj2)); // False
You can see the Equals behave differently which make Distinct behave differently. The problem is not var you mentioned in your question but AnonoymizeType
To make Distinct works as you expect, you need to override Equals and GetHashCode
public class InventoryDetails
{
public int? PersonalInventoryGroupId { get; set; }
public int? PersonalInventoryBinId { get; set; }
public override bool Equals(object obj)
{
if (obj == null) return false;
if (obj is InventoryDetails)
{
if (PersonalInventoryGroupId == (obj as InventoryDetails).PersonalInventoryGroupId
&& PersonalInventoryBinId == (obj as InventoryDetails).PersonalInventoryBinId)
return true;
}
return false;
}
public override int GetHashCode()
{
int hash = 17;
hash = hash * 23 + PersonalInventoryBinId.GetHashCode();
hash = hash * 23 + PersonalInventoryGroupId.GetHashCode();
return hash;
}
}
Another approach would be
List<InventoryDetails> inventory = (from i in TempTbl
where i.TempId == id
select new InventoryDetails
{
PersonalInventoryBinId = i.PersonalInventoryBinId,
PersonalInventoryGroupId = i.PersonalInventoryGroupId,
}).AsQueryable().ToList().Distinct(new customComparer()).ToList();
public class customComparer:IEqualityComparer<InventoryDetails>
{
public bool Equals(InventoryDetails x, InventoryDetails y)
{
if (x.TempId == y.TempId && x.PersonalInventoryBinId == y.PersonalInventoryBinId
&& x.PersonalInventoryGroupId == y.PersonalInventoryGroupId)
{
return true;
}
return false;
}
public int GetHashCode(InventoryDetails obj)
{
return string.Concat(obj.PersonalInventoryBinId.ToString(),
obj.PersonalInventoryGroupId.ToString(),
obj.TempId.ToString()).GetHashCode();
}
}
As said in a comment by Ivan, you make your life difficult by calling ToList before Distinct. This prevents the SQL provider from incorporating the Distinct call into the generated SQL statement. But that leaves the question: what causes the difference?
The first query generates anonymous type instances. As per the C# specification, by default anonymous types (in C#) are equal when their properties and property values are equal (structural equality). Conversely, by default, reference types (like InventoryDetails) are equal when their reference (say memory address) is equal (reference equality or identity). They can be made equal by overriding their Equals and GetHashcode methods, as some people suggested to do.
But that's not necessary if you remove the first ToList():
var inventory = (from i in _context.TempTbl
where i.TempId == id
select new InventoryDetails
{
PersonalInventoryBinId = i.PersonalInventoryBinId,
PersonalInventoryGroupId = i.PersonalInventoryGroupId,
}).Distinct().ToList();
Now the whole statement until ToList() is an IQueryable that can be translated into SQL. The SQL is executed and the database returns a distinct result set of raw records from which EF materializes InventoryDetails objects. The C# runtime code was even never aware of duplicates!
here is my table:
table name: data
fields:
Id
category
description
imagePath
I'm building a webApi that returns all imagePath or by id.
web api controller:
namespace task.Controllers
{
public class ImagesController : ApiController
{
DataEntry db = new DataEntry();
public IEnumerable<datum> GetImages()
{
var imagePath = from m in db.data select m;
return imagePath;
}
public IHttpActionResult GetImages(int id)
{
var imagePath = from m in db.data select m;
var imagPath = imagePath.Where((p) => p.Id == id);
if (imagePath == null)
{
return NotFound();
}
return Ok(imagePath);
}
}
}
It's returning all fields (Id,category, description and imagePath) instead of imagePath only.and for the select by Id method it's not working also, so what is wrong??
For the imagePath, try specifying it in the linq query like so:
public IEnumerable<string> GetImages()
{
var imagePath = from m in db.data select m.imagePath;
return imagePath.ToList();
}
For the select by id, try this:
public string GetImages(int id)
{
var imagePath = from m in db.data select m;
var imagPath = imagePath.Where((p) => p.Id == id);
if (imagPath == null)
{
return NotFound();
}
return Ok(imagPath.imagePath);
}
Double check for typo such as imagPath and imagePath too
I'm trying to get the userid of the currently logged in user. Here is my code:
public int GetUserID(string _UserName)
{
using (var context = new TourBlogEntities1())
{
var UserID = from s in context.UserInfoes
where s.UserName == _UserName
select s.UserID;
return Int32.Parse(UserID.ToString()); //error is showing here
}
}
I'm calling the method from my controller using this:
public ActionResult NewPost(NewPost model)
{
var Business = new Business();
var entity = new Post();
entity.PostTitle = model.PostTitle;
entity.PostStory = model.PostStory;
entity.UserID = Business.GetUserID(User.Identity.Name);
Business.NewPost(entity);
Business.ViewPost(entity);
return View("ViewPost", model);
}
The error is showing as "input string is not in correct format". Please help. Thanks.
Your query returns an IEnumerable. You need to get only the single record:
using (var context = new TourBlogEntities1())
{
var userIds = from s in context.UserInfoes
where s.UserName == _UserName
select s.UserID;
return userIds.Single();
}
By the way the .Single() method will throw an exception if there are more than 1 records matching the criteria. Hopefully you have an unique constraint on the Username field inside your database.
CreatedBy = this.HttpContext.User.Identity.Name,
When I run this line of code
queryCompanies = (DbSet)queryCompanies.Include(path);
from this method:
public Company GetCompanyById(int companyId)
{
List<string> includePaths = new List<string>();
includePaths.Add("Addresses");
includePaths.Add("Users");
Company company = null;
using (Entities dbContext = new Entities())
{
var queryCompanies = dbContext.Companies;
if (includePaths != null)
{
foreach (string path in includePaths)
queryCompanies = (DbSet<Company>)queryCompanies.Include(path);
}
company = (from c in queryCompanies
where c.Id.Equals(companyId)
select c).FirstOrDefault<Company>();
}
return company;
}
I get this error:
Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery1[ClassLibrary1.Company]' to type 'System.Data.Entity.DbSet1[ClassLibrary1.Company]'.
At compilation I have no error. In EF 4.0 this code runs correct using instead of DbSet<>, ObjectQuery<>.
I am a beginner in EF 4.1 so any suggestion will be useful.
Thanks.
Try this
public Company GetCompanyById(int companyId)
{
List<string> includePaths = new List<string>();
includePaths.Add("Addresses");
includePaths.Add("Users");
Company company = null;
using (Entities dbContext = new Entities())
{
var queryCompanies = dbContext.Companies.AsQueryable();
if (includePaths != null)
{
foreach (string path in includePaths)
queryCompanies = queryCompanies.Include(path);
}
company = (from c in queryCompanies
where c.Id.Equals(companyId)
select c).FirstOrDefault<Company>();
}
return company;
}
DbSet inherits from DbQuery, so the compiler doesn't complain since the cast could be valid. Apparently, what DbSet<T>.Include returns is not a DbSet<T> and the cast fails at runtime.
However, you do not need to cast; calling FirstOrDefault will work on DbQuery<T>.
I write a generic include checker method. This is not good now but it is work. I will refactor this. Maybe it meets your needs.
List<TEntityType> GetEntityListTemplate(Expression<Func<TEntityType, bool>> expression = null)
{
List<TEntityType> entityList;
DbQuery<TEntityType> query = null;
Type entityType = typeof(TEntityType);
PropertyInfo[] properties = entityType.GetProperties();
using (DatabaseContext database = new DatabaseContext())
{
database.Database.Connection.Open();
foreach (PropertyInfo property in properties)
{
if (property.PropertyType.FullName.Contains("Your.Identifier.Namespace"))
{
if (query == null)
{
query = database.Set<TEntityType>().Include(property.Name);
}
else
{
query = query.Include(property.Name);
}
}
}
if (query == null)
{
if (expression == null)
{
entityList = database.Set<TEntityType>().ToList();
}
else
{
entityList = database.Set<TEntityType>().Where(expression).ToList();
}
}
else //(query!=null)
{
if (expression == null)
{
entityList = query.ToList();
}
else
{
entityList = query.Where(expression).ToList();
}
}
}
return entityList;
}
I am performing a select query using the following Linq expression:
Table<Tbl_Movement> movements = context.Tbl_Movement;
var query = from m in movements
select new MovementSummary
{
Id = m.DocketId,
Created = m.DateTimeStamp,
CreatedBy = m.Tbl_User.FullName,
DocketNumber = m.DocketNumber,
DocketTypeDescription = m.Ref_DocketType.DocketType,
DocketTypeId = m.DocketTypeId,
Site = new Site()
{
Id = m.Tbl_Site.SiteId,
FirstLine = m.Tbl_Site.FirstLine,
Postcode = m.Tbl_Site.Postcode,
SiteName = m.Tbl_Site.SiteName,
TownCity = m.Tbl_Site.TownCity,
Brewery = new Brewery()
{
Id = m.Tbl_Site.Ref_Brewery.BreweryId,
BreweryName = m.Tbl_Site.Ref_Brewery.BreweryName
},
Region = new Region()
{
Description = m.Tbl_Site.Ref_Region.Description,
Id = m.Tbl_Site.Ref_Region.RegionId
}
}
};
I am also passing in an IFilter class into the method where this select is performed.
public interface IJobFilter
{
int? PersonId { get; set; }
int? RegionId { get; set; }
int? SiteId { get; set; }
int? AssetId { get; set; }
}
How do I add these where parameters into my SQL expression? Preferably I'd like this done in another method as the filtering will be re-used across multiple repositories.
Unfortunately when I do query.Where it has become an IQueryable<MovementSummary>. I'm assuming it has become this as I'm returning an IEnumerable<MovementSummary>. I've only just started learning LINQ, so be gentle.
Answer:
private IQueryable<Tbl_Docket> BuildQuery(IQueryable<Tbl_Docket> movements, IMovementFilter filter)
{
if (filter != null)
{
if (filter.PersonId.HasValue) movements = movements.Where(m => m.UserId == filter.PersonId);
if (filter.SiteId.HasValue) ...
}
return movements;
}
Which is called like follows:
var query = from m in this.BuildQuery(movements, filter)
select new... {}
You have to call the where statement before you fire your select statement, e.g.:
IQueryable<Tbl_Movement> movements = context.Tbl_Movement;
if (filter != null)
{
if (filter.PersonId != null) movements = movements.Where(m => m....PersonId == filter.PersonId);
if (filter.RegionId != null) movements = movements.Where(m => m....RegionId == filter.RegionId);
if (filter.SiteId != null) movements = movements.Where(m => m...SiteId == filter.SiteId);
if (filter.AssetId != null) movements = movements.Where(m => m...AssetId == filter.AssetId);
}
var query = m from movements...
As opposed to using this IFilter class, you might want to consider a Fluent Pipe-based Repository structure, e.g.:
var movements = new MovementsPipe()
.FindSiteId(1)
.FindAssetIds(1, 2, 3)
.FindRegionId(m => m > 10)
.ToMovementSummaryList();
Hope this helps. Let me know if you have any questions.