Question considering LINQ to Excel - c#

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

Related

How to write LINQ query for fetching the specific records and generating new result at the same time?

I have to update one field in the row of the table after fetching two records from the same row. As an easiest practice I have fetched two records individually, created a new value and then updating that particular property through Entity framework. I think there is a better way to do the same thing with less code. If any body can suggest please.
if (objModel.amountpaid==0)
{
using (estatebranchEntities db=new estatebranchEntities())
{
int rentVar = Convert.ToInt32(db.PropertyDetails.Where(m => m.propertyid == objVM.propertyid).Select(m => m.rent).SingleOrDefault());
int balanceVar = Convert.ToInt32(db.PropertyDetails.Where(m => m.propertyid == objVM.propertyid).Select(m => m.balance).SingleOrDefault());
int balanceUpdateVar = (rentVar + balanceVar);
var propInfo = new PropertyDetail() { balance = balanceUpdateVar };
//var result = (from a in db.PropertyDetails
// where a.propertyid == objVM.propertyid
// select new PropertyDetail
// {
// rent = a.rent,
// balance = a.balance
// }).ToList();
db.PropertyDetails.Attach(propInfo);
db.Entry(propInfo).Property(z => z.balance).IsModified = true;
db.SaveChanges();
}
}
Here is what I think you can do.
Fetch the data once and update once.
using (estatebranchEntities db=new estatebranchEntities())
{
var propDetails = db.PropertyDetails.FirstOrDefault(m => m.propertyid == objVM.propertyid);
if (propDetails != null)
{
int rentVar = Convert.ToInt32(propDetails.rent);
int balanceVar = Convert.ToInt32(propDetails.balance);
int balanceUpdateVar = rentVar + balanceVar;
//now do the update
propDetails.balance = balanceUpdateVar;
db.Entry(proDetails).State = EntityState.Modified;
db.SaveChanges();
}
}
if you need to use the rentVar,balanceVar or the balanceUpdateVar, outside of the using statement then declare them outside it.

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

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

Populating textboxes using LINQ2SQL

In my web forms, I have text boxes and one radiolist which I need to populate through a LINQ2SQL query. So far I coded this query to fetch particular records which is going to be populated into the DB.
using (dbTestDataContext db = new dbTestDataContext())
{
var query = from r in db.Table1
where r.Code == getCode
select new
{
//Account Info
r.Name,
r.Num,
r.AcctNum,
r.CorpAcct, //Bool
};
};
Now I know that the record which this query is going to be fetching is gonna be only 1 unique record. I want to show the record in these textboxes and select that radio button:
tbName
tbNum
tbAcctNum
rbtnCorpAcct
How should I do this? Thank you in advance!
Very simply:
using (dbTestDataContext db = new dbTestDataContext())
{
var query = (from r in db.Table1
where r.Code == getCode
select new
{
//Account Info
r.Name,
r.Num,
r.AcctNum,
r.CorpAcct, //Bool
}).FirstOrDefault();
if (query != null)
{
tbName.Text = query.Name;
tbNum.Text = query.Num;
//and so on
rbl.SelectedValue = query.SomeValue;
}
};
Same as others have answered with addition of radio button:
tbName.Text = query.Name;
tbNum.Text = query.Num;
tbAcctNum.Text = query.AcctNum;
if(query.CorpAcct)
rbtn.SelectedValue = "Yes"; \\Where "Yes" is one of the radio button values
else
rbtn.SelectedValue = "No";
\\Could also use SelectedIndex, rbtn.SelectedIndex = 0 or 1
Try the following:
using (dbTestDataContext db = new dbTestDataContext())
{
var query =
(
from r in db.Table1
where r.Code == getCode
select new
{
//Account Info
r.Name,
r.Num,
r.AcctNum,
r.CorpAcct, //Bool
}
).FirstOrDefault();
tbName.Text = query.Name;
....
};
The first thing you need to do is retrieve a single result from your query. As you have it written, you are returning an IQueryable object which is now stored in the variable "query"
To get a single object, do this
var myObject = query.SingleOrDefault();
Then you can access the individual properties of that object and assign them like this
tbName.Text = myObject.Name

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