I'm look at learning a bit more ASP.Net MVC and Linq To Entity.
I'm working on a project using this and am having a problem with the following line of code
ViewData["ProjectName"] = db.Projects.FirstOrDefault(p => p.ProjectId == task.ProjectId).ProjectName;
It works fine when the record exists but if no record exist it errors because I am trying to examine the ProjectName property of a null object. I realise I could cast the object to a variable and test if its null before storing the ProjectName into the ViewData but am just wondering if there is a neater way of doing this?
I know its a simple question and I could just work around it but if there is a better way of doing this it would be good to know.
Thanks
Gavin
var project = db.Projects.FirstOrDefault(p => p.ProjectId == task.ProjectId);
if (project != null)
{
ViewData["ProjectName"] = project.ProjectName;
}
else
{
//........
}
No cast needed.
Or skip the condition altogether and do this:
ViewData["ProjectName"] = db.Projects.Where(p => p.ProjectId == task.ProjectId)
.Select(p => p.ProjectName).FirstOrDefault();
Related
I am working on MVC4 App, and I am stuck at one point, I tried using google to help me, but without success. This might be more simple then I think, but coming from web forms and shifting to mvc is "painful" sometime.
I am trying to loop through the model I have and get the values stored in that model. I tried few approaches but I am getting an error everytime. This is what I have:
var modelAgentFilter = from s in _aa.Agents
where s.COUNTER == Convert.ToInt32(AgentID)
select s;
if (modelAgentFilter != null)
{
ViewBag.FirstName = // Get FirstName object here
}
Thanks in advance for your comments.
Laziale
EDIT:
I did include for loop like this:
if (modelAgentFilter != null)
{
foreach (var property in modelAgentFilter)
{
string test = property.ADDRESS;
}
}
But when the compiler will reach the foreach step I am getting this error: "LINQ to Entities does not recognize the method 'Int32 ToInt32(System.Object)' method, and this method cannot be translated into a store expression."
I can get to the properties of the var model using that foreach look but as soon as the compiler will try to loop the model that error pops up.
Thanks again
LINQ to Entities does not recognize any methods. You can't use even ToString() in LINQ expression. You need first convert your value and than add it in LINQ.
In your example you need to do something like following:
var _agentID = int.Parse(AgentID);
var modelAgentFilter = from s in _aa.Agents
where s.COUNTER == _agentID
select s;
I have the following Linq Expession being used in EF 4
var map = model.CDM_SubsidiaryDocumentMap.Where(m => m.SubsidiaryID == subsidiaryID)
.Include("CDM_DocumentType")
.Include("CDM_DocumentType.CDM_DocumentHeader")
**(Need Help here) Filter based on CDMDocumentType.CDM_DocumentHeader.ContactID == 123**
.OrderBy(m => m.UISortOrder)
.ToList();
How do I write the missing statement above, where in I include the nested child based on contactID filter. Also note that CDM_DocumentType.CDM_DocumentHeader is a collection. Much appreciated
If you don't mind using the from syntax. Try something like this:
var map = (from m in model.CDM_SubsidiaryDocumentMap
from dmh in m.CDM_DocumentType.CDM_DocumentHeader
where m.SubsidiaryID == subsidiaryID
&& dmh.ContactID == 123
order by m => m.UISortOrder
select m).ToList();
If that doesn't work show more of your Entity Model, as I made and assumtion that CDM_DocumentType is a navigation property on CDM_SubsidiaryDocumentMap.
I have searched for quite a while, but I have not found any thread explaining how exactly to find out which Tenant is the current one in code. For example, I want to change some logic based off of what Tenant is active like so:
IQueryable<ContentPartRecord> getContentPartDates;
if (Tenat == ExampleTenant)
{
getContentPartDates = GetContentPartDates((int)Id)
.Where(ss => ss.SalesStatus == "Guaranteed")
.OrderBy(x => x.start_date);
}else {
getContentPartDates = GetContentPartDates((int) Id).OrderBy(x => x.start_date);
}
What exactly is the best way to do this?
Thanks in advance.
Inject ShellSettings in ctor. This object contains all data (from Settings.txt file) about the shell (ie. tenant) in which current unit of work executes.
Not sure how this is done, I have my .edmx set up so that the navigation properties match the foreign key relationships on the tables. Not sure if I still need to perform joins or if EF will give me access to the related table data through the navigational properties automatically.
What I need to do it get all the ContentSections and their associated ContentItems based on the ContentView and filtered by the DiversionProgram.CrimeNumber.
I would like to get back IEnumerable, for each ContentSection it should have access to it's ContentItems via the navigation property ContentItems
Thanks
Something like:
using(Entities context = new Entities())
{
IEnumerable<ContentSection> enumerator = context.ContentSections
.Include("ContentItems")
.Where<ContentSection>(cs => cs.ContentView.ContentViewID == someID && cs.ContentItems.Where<ContentItem>(ci => ci.DiversionProgram.CrimeNumber == someCrimeNumber))
.AsEnumerable<ContentSection>
}
I've interpreted
based on the ContentView
as cs.ContentView.ContentViewID == someID
This will give you all the ContentSections for a given ContentView. And interpreted
filtered by the DiversionProgram.CrimeNumber
as cs.ContentItems.Where<ContentItem>(ci => ci.DiversionProgram.CrimeNumber == someCrimeNumber)
which will give you all those ContentItems that have a specific CrimeNumber.
Or did you mean something else with based on / filtered by. Maybe OrderBy, or all those ContentSections where Any of it's ContentItems would have a certain CrimeNumber?
You can eager load to get all associated records, but when you want to start filtering/ordering, don't bother with Include.
Just do a projection with anonymous types and EF will work out what it needs to do. It's a bit hairy, but it'll work. If it get's too complicated, bite the bullet and use a SPROC.
Now, with that caveat, something like this (off the top of my head):
var query = ctx.ContentView
.Select(x => new
{
ContentSections = x.ContentSections
.Where(y => y.ContentItems
.Any(z => z.DivisionProgram.CrimeNumber = 87))
}).ToList().Select(x => x.ContentSections);
If you use the CTP5 you can do something very unique it looks like this:
var context = new YourEntitiesContext();
var query = context.ContentView.Include(cs => cs.ContentSections
.Select(ci => ci.ContentItems
.Select(dp => dp.DiversionProgram)
.Where(dp.CrimeNumber == crimeNumber)))
.Where(cv => cv.ContentViewID == contentViewID).FirtsOrDefault();
You can learn more about the CTP5 and how it can be used in Database first scenario here
var query = from t1 in studentManagementEntities.StudentRegistrations
join t2 in studentManagementEntities.StudentMarks
on t1.StudentID equals t2.StudentID
select new
{
t1.selected column name,
t2.selected column name
};
Hi
How can i filter results exists in BindingSource filled with entities ( using EF 4)?
I tried this:
mybindingsource.Filter = "cityID = 1"
But it seems that binding source with entity framework doesn't support filtering .. am i right ?,is there another way to filter(search) data in binding source .
PS:
- I'm working on windows application not ASP.NET.
- I'm using list box to show the results.
Thanx
Maybe a better one than Leonid:
private BindingSource _bs;
private List<Entity> _list;
_list = context.Entities;
_bs.DataSource = _list;
Now when filtering is required:
_bs.DataSource = _list.Where<Entity>(e => e.cityID == 1).ToList<Entity>;
This way you keep the original list (which is retrieved once from the context) and then use this original list to query against in memory (without going back and forth to the database). This way you can perform all kinds of queries against your original list.
I think, you have made mistake in syntax. You should write Filter like this:
mybindingsource.Filter = "cityID = '1'"
Another way is to use LINQ expressions.
(About LINQ)
Why do you have to call Entety again?
Simple solution:
public List<object> bindingSource;
public IEnumerable FiltredSource
{
get{ return bindingSource.Where(c => c.cityID==1);
}
.where (Function (c) c.cityID = 1)