How to retrieve class object from ICollection? - c#

I have 2 classes Users and Userdetails.
User contains Userdetails ICollection;
public class Users
{
public int Id;
public ICollection<Userdetails> Userdetails;
}
I want to retrieve a UserDetails object from a User object but could not find a way;
I have implemented it in this way:
var lstUserdetails = new List<Userdetails>();
lstUserdetails = (from e in user.Userdetails
select e).ToList();
var userobject = ((Userdetails)lstUserdetails.Find(x=>x.id == Id));
but it is showing userobject null.
How to resolve it?

var userDetailsObejct = (from u in user.UserDetails
where u.id == Id
select u).FirstOrDefault();
This will return a UserDetails object from the UserDetails collection from a specified user with an id that's equal to Id. If it doesn't find it, it will return null.

Try this
var lstUserdetails = new List<Userdetails>();
lstUserdetails = (from e in user.Userdetails where e.id == Id
select e).Firstordefault();

Related

Right way to delete a row in ado.net entity data model

I need to delete a row using ado.net entity data model. Already googling about this, but i still can't find out how to do it right.
Here's my code:
else if (mode == 3)
{
LaundryEntities1 db = new LaundryEntities1();
var query = (from user in db.Users
where user.UserID == textBoxID.Text
select user).First();
db.DeleteObject(query);
db.SaveChanges();
reload();
MessageBox.Show("Succesfully delete a user");
clear();
}
You can use
LaundryEntities1 db = new LaundryEntities1();
var query = (from user in db.Users
where user.UserID == textBoxID.Text
select user).First();
db.Entry(employer).State = EntityState.Deleted
if(db.SaveChanges())
MessageBox.Show("Succesfully delete a user");
I make a public class named Session
public class session
{
public static DatabaseEntities db = new DatabaseEntities();
public static User user = null;
}
and changed my code into
Users user = (from x in session.db.Users
where x.UserID == textBoxID.Text
select x).FirstOrDefault();
session.db.Users.DeleteObject(user);
session.db.SaveChanges();

get value from another tabe for two same field in a table

i have a view where i get data from a table named 'PromotionHistory'. But in my table i stored ID of Designation. In Designation table i have DesignationName field and DesignationID. Both table have relation. I am using Web Api.
My code-
[HttpGet]
[Route("api/EmployeeApi/GetPromotionReport/")]
public object GetPromotionReport()
{
List<PromotionHistory> finalData;
//var proReport = db.PromotionHistories.Include(e => e.Designation).Include(e => e.Employee);
IEnumerable<PromotionHistory> pro = (from st in db.PromotionHistories select st).ToList();
foreach (PromotionHistory proH in pro)
{
var preD = proH.PreviousDesigID;
var currentD = proH.CurrentDesigID;
var preDName=(from dd in db.Designations where dd.DesignationID==preD select new{dd.DesignationName}).FirstOrDefault() ;
var CurrentDName=(from dd in db.Designations where dd.DesignationID==currentD select new{dd.DesignationName}).FirstOrDefault();
var cc = (from proHis in db.PromotionHistories
select new
{
proHis.PromotionID,
proHis.EmployeeID
}
).ToList();
finalData.AddRange(cc);
finalData.Add(preDName);
}
I want to get DesignationName instead of ID for the two field (previousPost, Current Post-see image)
How can i make Linq or SQL query in ASP Web Api as i am using Ajax.
What i want::
PromotionID ,EmplyeeID ,PromotionDate, Previous Designation , Current Designation
You can add another class, and return list of the new class. like this
public object GetPromotionReport()
{
List<PromotionHistorywithNames> finalData;
finalData = (from st in db.PromotionHistories
select new PromotionHistorywithNames
{
PromotionID = st.PromotionID,
EmployeeID = st.EmployeeID,
PreviousPost = (from dd in db.Designations where dd.DesignationID == st.Promotion select dd.DesignationName).FirstOrDefault(),
CurrentPost = (from dd in db.Designations where dd.DesignationID == st.currentD select dd.DesignationName).FirstOrDefault()
}).ToList();
return finalData;
}
and the class like this
public class PromotionHistorywithNames{
public int PromotionID{set;get;}
public int EmployeeID{set;get;}
public DateTime Promotion{set;get;}
public string PreviousPost{set;get;}
public string CurrentPost{set;get;}
}
I solved my annonymous type problem by this: It can be done without model class
[HttpGet]
[Route("api/MemberApi/GetMembersWithLink/")]
public object GetMembersWithLink()
{
var member = (from members in db.Members
where members.Status == 1
select new
{
members.MemberName,
members.Position,
members.Phone,
members.Picture,
members.MotherName,
members.Village,
members.Email,
linkName = (from gg in db.Members where gg.MemberID== members.Link select gg.MemberName).FirstOrDefault()
}).ToList();
return member.AsEnumerable();
}

How do I return only one contact per organization?

I have to return only the primary contact within an account of a person that is a member, but my query is returning all all members within the organization. I have tried reordering it and using stuff like Single() but with no luck. I need a way to put a where clause that says I only want the Primary Contact with an account.
if ((!string.IsNullOrEmpty(organization)) && (!string.IsNullOrEmpty(city)) && state != null)
{
var corporatemembers = (from a in crmContext.bpt_membertypeSet
where a.bpt_membertypename == "Member (Individual)" || a.bpt_membertypename == "Courtesy"
|| a.bpt_membertypename == "Affiliate" || a.bpt_membertypename == "Member"
select new { a.Id }).ToList();
foreach (var corporatemember in corporatemembers)
{
var directories = (from b in crmContext.AccountSet
join a in crmContext.ContactSet
on b.Id equals a.ParentCustomerId.Id
where a.bpt_MemberTypeId.Id == corporatemember.Id
where a.bpt_memberstatus == (int)bpt_memberstatus.Active
where b.Name.Contains(organization)
where a.Address1_City.Contains(city)
where a.bpt_stateorusterritory.Value == state.Value
select new { b.PrimaryContactId, b.EMailAddress1, a.Address1_City, b.Name, b.WebSiteURL, a.bpt_stateorusterritory }).ToList();
foreach (var directory in directories.ToList().OrderBy(o => o.Name))
{
var cityState = String.Empty;
if (directory.bpt_stateorusterritory != null)
cityState = directory.Address1_City + ", " + Utility.GetOptionSetValueLabel(crmContext, new Microsoft.Xrm.Sdk.Entity(Xrm.Contact.EntityLogicalName), "bpt_stateorusterritory", new Microsoft.Xrm.Sdk.OptionSetValue(directory.bpt_stateorusterritory.Value));
else
cityState = directory.Address1_City;
oMemberList.Add(new Members { FullName = directory.PrimaryContactId, FullNameEmail = directory.EMailAddress1, OrganizationName = directory.Name, OrganizationUrl = directory.WebSiteURL, CityState = cityState });
}
}
}
this code returns all if the search categories are all filled. I have 4 clauses for all scenarios. But at the end of the whole thing I have:
oMembers.ToList()
Thanks
Edit: here is sample data but the output is wrong. There should only be one organization and one contact
I think you are using the wrong field for the join here. This would return all contacts who are a child of that account - which is probably why you are getting multiple results.
on b.Id equals a.ParentCustomerId.Id
The primary contact field on the account is primarycontactid so I suggest you update your query to reference that attribute instead.

Select properties for particular entities LINQ

You can probably see the result I want to get. It's easy using loop, but I can't understand how to achieve such result using LINQ extension methods
I have two contexts that target one DB. ApplicationUser is authentication class, and profileDTO profile info that I get from same DB.
ProfileDTO properties: string Id, string FirstName, string LastName
Both tables share same ID but are not connected neither through navigation properties nor any references in the DB.
IEnumerable<ViewModels.User.IndexViewModel> model;
IEnumerable<Models.ApplicationUser> users;
var profilesDtos = _profileService.GetAll();
using (var context = new Models.ApplicationDbContext())
{
users = context.Users.ToList();
}
model = users.Select(user =>
new ViewModels.User.IndexViewModel
{
Id = user.Id,
Email = user.Email,
PhoneNumber = user.PhoneNumber,
LockedOutTill = user.LockoutEndDateUtc ?? default(DateTime),
Roles = UserManager.GetRoles(user.Id)
});
foreach (var user in model)
{
var userProfile = profilesDtos.FirstOrDefault(o => o.Id == user.Id);
if (userProfile != null)
{
user.FirstName = userProfile.FirstName;
user.LastName = userProfile.LastName;
}
};
I want to get all users but with Names set only in those who have profiles.
You can use left join in Linq, like below -
IEnumerable<ViewModels.User.IndexViewModel> model;
IEnumerable<Models.ApplicationUser> users;
var profilesDtos = _profileService.GetAll();
using (var context = new Models.ApplicationDbContext())
{
users = context.Users.ToList();
}
model = (from u in users
join p in profilesDtos on u.Id equals p.Id into tempTbl
from up in tempTbl.DefaultIfEmpty()
select new ViewModels.User.IndexViewModel
{
Id = u.Id,
Email = u.Email,
PhoneNumber = u.PhoneNumber,
LockedOutTill = u.LockoutEndDateUtc ?? default(DateTime),
Roles = UserManager.GetRoles(u.Id),
FirstName = up!= null? up.FirstName : string.Empty;
LastName = up!= null? up.LastName : string.Empty;
}).ToList();
First of all I would suggest to update your context to setup such property. If you can't do this use JOIN:
var result =
from user in context.Users
join profile in userProfiles on user.ID equals profile.ID
select new ViewModels.User.IndexViewModel {
Id = user.Id,
FirstName = profile.FirstName,
...
}
As a solution, you can just join them.
MSDN
Plus DefaultIfEmpty statement.

Excel Data using LinQ Intersecting

My intersect in LINQ somehow dont seem to work. I have two excel sheets. I fetch it using LinQToExcel and (LinQToExcel does not support VisitSubQueryExpression i have to do some extra work).
List<BoardSheet> sourceTest = (from t in Boards[0]
where t["Board"] == boardName
select new CircuitSet
{
ID = string.Format(t["ID"]),
Data = string.Format(t["Data"]),
CtrlType = string.Format(t["CtrlType"]),
sys = string.Format(t["sys"]),
code = string.Format(t["code"])
}
).ToList<BoardSheet>();
List<BoardSheet> targetTest = (from t in Boards[0]
where t["Board"] == boardName
select new CircuitSet
{
ID = string.Format(t["ID"]),
Data = string.Format(t["Data"]),
CtrlType = string.Format(t["CtrlType"]),
sys = string.Format(t["sys"]),
code = string.Format(t["code"])
}
).ToList<BoardSheet>();
IEnumerable<BoardSheet> board = sourceTest.Intersect(targetTest);
board's count always returns 0. But when i iterate thro the field values of sourceTest and targetSet i see common field values.
These are instances of reference types. Intersect is using the DefaultComparer for reference types, which is ReferenceEquals. Since sourceTest has no common instances with targetTest, no results are found.
You could create a Comparer, or you could join like this:
List<CircuitSet> results =
(
from s in sourceTest
join t in targetTest
on s.Id equals t.Id
where s.Data == t.Data && s.ControlType == t.ControlType ...
select s
).ToList();
I think an easy way would be to implement IEqualityComparer<CircuitSet>. If CircuitSet's key is ID, then you could do it like this:
public class CircuitSetComparer : IEqualityComparer<CircuitSet>
{
#region IEqualityComparer<CircuitSet> Members
public bool Equals(CircuitSet x, CircuitSet y)
{
return x.ID == y.ID;
}
public int GetHashCode(CircuitSet obj)
{
return obj.ID;
}
#endregion
}
Then in your code:
IEnumerable<BoardSheet> board = sourceTest.Intersect(targetTest, new CircuitSetComparer());
GetHashCode method is tricky though, but it should be alright if my assumptions (ID being the key) are correct.
but i changed the query based on what david suggested
List<BoardSheet> sourceTest =(from s in (from t in Boards[0]
where t["Board"] == boardName
select new CircuitSet
{
ID = string.Format(t["ID"]),
Data = string.Format(t["Data"]),
CtrlType = string.Format(t["CtrlType"]),
sys = string.Format(t["sys"]),
code = string.Format(t["code"])
}
).ToList<BoardSheet>() jon tbl in (from t in Boards[0]
where t["Board"] == boardName
select new CircuitSet
{
ID = string.Format(t["ID"]),
Data = string.Format(t["Data"]),
CtrlType = string.Format(t["CtrlType"]),
sys = string.Format(t["sys"]),
code = string.Format(t["code"])
}
).ToList<BoardSheet>() on s.ID equals tbl.ID select s).ToList<BoardSheet>() ;

Categories

Resources