Item_SubContractor Item = (
from Isc in db.Item_SubContractors
where Isc.SubContract_id == tempSubContractId
&& Isc.Item_id == BOQItem.id
select Isc).ToList().FirstOrDefault();
Item is returning NULL, when db.Item_SubContractors, tempSubContractId, BOQItem.id all return something when I break point and run through it
Someone has any ideas how can I solve this problem?
Thanks
the FirstOrDefault() will return NULL if you don't have the value in your Database then be sure that the same item exist in your database
you can test this
bool exist = db.Item_SubContractors.Any(
Isc=> Isc.SubContract_id == tempSubContractId
&& Isc.Item_id == BOQItem.id)
to check if you have this item in your database
Related
I'm having a bit of trouble trying to find if my url parameters exist or not.
I have tried the following:
// doesn't work
(Request.QueryString["showTop"] != "" && Request.QueryString["showTop"] != null)
// doesn't work
(Request.Params["showTop"] != "" && Request.Params["showTop"] != null)
I am trying to find the correct value. The full statement looks like:
showTop = (Request.QueryString["showTop"] != "" &&
Request.QueryString["showTop"] != null) ?
Request.QueryString["showTop"] : (10).ToString();
Which works fine, if showTop exists with a value.
This is being done within the view.
Try the following:
showTop = string.IsNullOrEmpty(Request["showTop"]) ? "10" : Request["showTop"];
Assuming you want "showTop"to default to "10".
First check whether QueryString has keys or not by calling this method.
bool qKeys = Request.QueryString.HasKeys();
I have, what I thought was a pretty straight-forward query.
In normal Sql this would read:
SELECT [column names]
FROM agentscheduledetail
WHERE (date = '2012-07-04') AND
(
exception = 'Break (No Sign Off)' OR
exception = 'Break' OR
exception = 'Break (Signed Out)'
)
This returns approx 900 records.
However, when I try to enter this into my controller, I end up with around 300,000 records - so I think my AND and ORs are not working. I've tried Linqer, but can't get it to work (I'm aware this may not be actual LINQ but the equivalent query in VS - if there is a linq version... I'd be grateful for that too if possible).
My controller query is:
var dte = DateTime.Today;
return View(db.agentscheduledetails.Where
(
d => d.date == dte && d.agentName.StartsWith("ta") &&
(
d.exception == "Break (No Sign Off)" ||
d.exception == "Break" ||
d.exception == "Break (Signed Out)"
)
).ToList()
);
Can anyone either a) let me know where I'm going wrong with my && || (and/or), or b) is there a way of stepping through the code in VS, to see what the above query translates to in normal SQL so I can try to figure out where I'm going wrong?
Thanks for any help,
Mark
The following is perhaps a simplified version of what you are trying to do, also your LINQ contains an additional statement compared to the SQL where it is comparing the agent name?
var currentDate = DateTime.Today;
var exceptionTypes = new List<string>() { "Break (No Sign Off)",
"Break", "Break (Signed Out)" };
db.agentscheduledetails.Where(d => d.date == currentDate &&
exceptionTypes.Contains(d.exception));
One thing that you could try is getting hold of a copy of LinqPad, this will let you run your LINQ statement against a database and will show you what the generated SQL statement is.
Aside from anything else,
d.agentName.StartsWith("ta")
does not appear in your original sql...?
I am trying to simply update the entity object and I get this error.. All the googling on the error I did takes me to complex explanations... can anyone put it simply?
I am working of of this simple tutorial
http://aspalliance.com/1919_ASPNET_40_and_the_Entity_Framework_4__Part_2_Perform_CRUD_Operations_Using_the_Entity_Framework_4.5
else
{
//UPDATE
int iFid = Int32.Parse(fid.First().fid.ToString());
oFinancial.fid = iFid;
oFinancial.mainqtr = currentQuarter;
oFinancial.mainyear = currentYear;
oFinancial.qtr = Int32.Parse(currentQuarter);
oFinancial.year = Int32.Parse(currentYear);
oFinancial.updatedate = DateTime.Now;
// ObjectStateEntry ose = null;
// if (!dc.ObjectStateManager.TryGetObjectStateEntry(oFinancial.EntityKey, out ose))
// {
dc.financials.Attach(oFinancial);
// }
dc.ObjectStateManager.ChangeObjectState(oFinancial, System.Data.EntityState.Modified);
}
dc.SaveChanges();
here is what is higher up in the code that I use simple to get me the primary key value.. probably a better way but it works.
var fid = from x in dc.financials
where iPhaseID == x.phaseid &&
strTaskID == x.ftaskid &&
strFundType == x.fundtype &&
iCurrentQuarter == x.qtr &&
iCurrentYear == x.year
select x;
If the oFinancial object came from your dc and you never manually detached it, then there is no reason to call the Attach method or to mess with the ObjectStateManager. As long as the dc knows about the object (which it does unless you detach it), then the ObjectStateManager will keep track of any changes you make and update them accordingly when you call dc.SaveChanges().
EDIT: Here's a refactored version of what you posted, hope it helps:
else {
//UPDATE
// as long as oFinancial was never detatched after you retrieved
// it from the "dc", then you don't have to re-attach it. And
// you should never need to manipulate the primary key, unless it's
// not generated by the database, and you don't already have another
// object in the "dc" with the same primary key value.
int iFid = Int32.Parse(fid.First().fid.ToString());
oFinancial.fid = iFid;
oFinancial.mainqtr = currentQuarter;
oFinancial.mainyear = currentYear;
oFinancial.qtr = Int32.Parse(currentQuarter
oFinancial.year = Int32.Parse(currentYear);
oFinancial.updatedate = DateTime.Now;
}
dc.SaveChanges();
One other thing: if iFid is the primary key, then you shouldn't mess with it as long as this object came from the dc. I believe the problem is that you're resetting the primary key (iFid) to the same value of another object within the dc, and EF4 is barking because you can't have two rows with the same primary key value in a table.
In the code bdehind && syntax does not work, any ideas?
Entities ctx3 = new Entities();
var uniqueQuote = from quot in ctx3.Quotes.Include("aspnet_Users").Include("Enquiries")
where quot.Enquiries.EnquiryId == selectedEnquiryId &&
quot.aspnet_Users.UserId == currentUserId
orderby quot.QuotePrice
select quot;
Error 2 Delegate 'System.Func' does not take '1' arguments C:\LocalGarageFinder\LocalGarageFinder\EnquiryDetail.aspx.cs 56 33 LocalGarageFinder
The code as written is fine. If you are receiving some sort of error, please let us know.
If EnquiryId or UserId is a Nullable type you will get the error. Use EnquiryId.Value == selectedEnquiryId or UserId.Value == currentUserId
I have a LINQ query like this:
from i in _db.Items.OfType<Medium>()
from m in i.Modules
from p in m.Pages
where i != null && i.Type == 1 && i.Published == true && p.PageId == 2
select p
I use the query like this because I have strongly typed view (ASP.NET MVC).
I need to have items sorted by the i.Sort property. orderby i.Sort and i.OrderBy(it => it.Sort) doesn't work. How can I fix this?
When sorting with Linq you usually give OrderBy a property, and eventually an IComparer, not a sorting function. For example:
class Person {
public int Age {get; set;}
}
public static void Main() {
var ps = new List<Person>();
ps.Add(new Person{Age = 1});
ps.Add(new Person{Age = 5});
ps.Add(new Person{Age = 3});
var sorted = ps.OrderBy(p => p.Age);
foreach(p in sorted) {
Console.WriteLine(p.Age);
}
}
Here Linq will know how to correctly sort integers.
Without giving more context (such as what exactly is i.Sort, what is its purpose, what do you want to do with it), it would be difficult to be more specific to your problem.
However, I'm pretty sure you are misunderstanding OrderBy: you should give it a lambda expression that identifies a property of the objects contained in your sequence, and then Linq will sort your sequence according to the usual order of the type of that property (or according to another order you define for that type, by using IComparer).
Let's say your Pages include page-numbers among their properties. Let's pretend this property is called "pagenumber". You would then add the following 'orderby' line between the 'where' and 'select' lines.
// (snip...)
where i != null && i.Type == 1 && i.Published == true && p.PageId == 2
orderby p.pagenumber
select p
Or maybe you don't have page numbers, but only page titles. You would do nearly the same thing:
where i != null && i.Type == 1 && i.Published == true && p.PageId == 2
orderby p.title
select p
Just from reading your code, I can't tell what criteria should be used for sorting. You need some kind of ordered element, an id number, a page number, or some text can be alphabetized.
from i in _db.Items.OfType<Medium>().OrderBy(x => x.Sort)
...