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

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();

Related

Sequence contains no matching element error when I try to getallUsers()

Hello my question is I have 2 table one is User table the other one is CustomerUsers I select them by Deleted=0 When I try to list all users and have customerId, I am having issue that sequence contains no matching element error
My Code is below any help would be appriciate
Thank you
My Dapper query is below :
public List<User> GetAllUsers()
{
List<User> user = new List<User>();
try
{
//var sql = #"SELECT * FROM [User] WHERE Deleted=0";
var sql = #"SELECT * from [User] u LEFT JOIN [CustomerUser] cu ON u.UserId = cu.CustomerUserId WHERE u.Deleted=0";
var lookUp = new List<User>();
using (var cn = Settings.Helper.ConnectionStringBiz())
{
cn.Open();
cn.Query<User,Customer,User>(sql,(u,c)=>
{
var myUser = lookUp.First(m => m.UserId == u.UserId);
if (myUser == null)
{
lookUp.Add(u);
myUser = u;
}
myUser.Customer = c;
return null;
},splitOn:"CustomerId");
}
return lookUp;
}
catch (Exception ex)
{
return user;
}
}
Issue generally occurs if your lookUp.First(m => m.UserId == u.UserId) didnt return any results.
You can use FirstOrDefault something like below instead of First which returns null (default value) if it didnt find any results for matching criteria.
var myUser = lookUp.FirstOrDefault(m => m.UserId == u.UserId);
Not sure why you are checking against lookUp, Its a new list that you created just before connecting to DB. It will always be empty (If I am not understanding it wrong).

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.

Entity Framework Database Submit

using the following code:
using (GagaShaggyContext db = new GagaShaggyContext())
{
ItemModel itemToChange = null;
itemToChange = (from i in db.Items
where i.ItemID == checkoutItem.Item.ItemID
select i).FirstOrDefault();
itemToChange.FrontFeature = false;
db.SaveChanges();
}
The model is saving back to the database with a brand new ID, which I want to save changes to the original database entry. Is there any reason for this to happen?
Thanks
Edit
On breakpoint analysis adding the receipt item before hand is adding a different ItemID not that I can see why:
using (var db = new GagaShaggyContext())
{
db.Receipts.Add(rec);
db.SaveChanges();
}
using (var db = new GagaShaggyContext())
{
var ItemToUse = (from i in db.ItemModels
where i.ItemModelID == checkoutItem.Item.ItemModelID
select i).FirstOrDefault();
rec.ItemModel = ItemToUse;
db.Receipts.Add(rec);
db.SaveChanges();
}
This fixed it. We need to actually retrieve the relevant Item and put it inside the Receipt (rec) then we could add it, now that Entity Framework recognizes the relationship between these two.
I guess you are trying to Insert into DB
using (GagaShaggyContext db = new GagaShaggyContext())
{
ItemModel itemToChange = new ItemModel();
itemToChange = (from i in db.Items
where i.ItemID == checkoutItem.Item.ItemID
select i).FirstOrDefault();
if(itemToChange !=null)
{
itemToChange.FrontFeature = false;
db .Items.Add(itemToChange);
db.SaveChanges();
}
}
If you are trying to Update the record than
using (GagaShaggyContext db = new GagaShaggyContext())
{
ItemModel itemToChange = new ItemModel();
itemToChange = (from i in db.Items
where i.ItemID == checkoutItem.Item.ItemID
select i).FirstOrDefault();
if(itemToChange !=null)
{
itemToChange.FrontFeature = false;
objDBContext.Entry(itemToChange).State = EntityState.Modified;
objDBContext.SaveChanges();
}
}

How to retrieve class object from ICollection?

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();

Question considering LINQ to Excel

I'm reading data from an XLS document, and I'm using the superb LINQ to Excel library.
The problem I have is more of a problem with dealing with LINQ.
I read new and updated incidents from an excel sheet. So I want check if the incident already exists in the database, and if it does I want to hook it up with that incident and then update it with all the new data from the excel that I've read. Some code:
var excel = new ExcelQueryFactory("filepath");
var getincident = from jj in excel.Worksheet<Incident>("Sheet1")
select jj;
foreach (var incident in getincident)
{
if (incident.CallId.Trim() == "")
break;
if (exists(incident.CallId, context))
{
incident.id = (from b in context.Incidents
where b.CallId == incident.CallId
select b.id
).First();
context.Incidents.Attach(incident, true);
}
else
{
context.Incidents.InsertOnSubmit(incident);
}
context.SubmitChanges();
}
and the exists is a simple check if the incident exists:
private bool exists(string piCallId, DataClasses1DataContext context)
{
return (from b in context.Incidents
where b.CallId == piCallId select b
).Any();
}
I need some way first to check if the incident exists before all the new data is added, and then submit the changes. Please help.
Does this do what you want?
var existingIncident =
(from b in context.Incidents
where b.CallId == incident.CallId
select b
).SingleOrDefault();
if (existingIncident != null)
{
existingIncident.xxx = incident.xxx;
existingIncident.yyy = incident.yyy;
...
}
else
context.Incidents.InsertOnSubmit(incident);

Categories

Resources