Cannot be constructed in a LINQ to Entities query. Error - c#

public ActionResult CreateApp(Guid id)
{
SMICParkingLotApplicationEntities1 dbb = new SMICParkingLotApplicationEntities1();
ApplicationDATA applicationData = (from a in dbb.ApplicationDATAs
where a.ApplicationID == id
select new ApplicationDATA
{
ApplicationID = a.ApplicationID,
BrandModel = a.BrandModel,
CrNo = a.CrNo,
OrNo = a.OrNo,
DatePosted = a.DatePosted,
PoR = a.PoR,
PlateNo = a.PlateNo,
VehicleType = a.VehicleType
}).FirstOrDefault();
ApplicationSlotViewModel applicationSlotViewModel = new ApplicationSlotViewModel
{
ApplicationDatas = applicationData,
Application = new Application()
};
return View(applicationSlotViewModel);
Dunno what to do it always shows this error Cannot be constructed in a LINQ to Entities query. Error Help Plss..

If the type of ApplicationDatas in your ViewModel is ApplicationDATA, you can set it directly with the result of your query:
var applicationData =dbb.ApplicationDATAs.FirstOrDefault(a=>a.ApplicationID == id);
ApplicationSlotViewModel applicationSlotViewModel = new ApplicationSlotViewModel
{
ApplicationDatas = applicationData,
Application = new Application()
};
You can't project the result of your query using an existing entity type. Check the post that I quote in my comment

Remove className after new keyword. Try below code.
var applicationData = (from a in dbb.ApplicationDATAs
where a.ApplicationID == id
select new
{
ApplicationID = a.ApplicationID,
BrandModel = a.BrandModel,
CrNo = a.CrNo,
OrNo = a.OrNo,
DatePosted = a.DatePosted,
PoR = a.PoR,
PlateNo = a.PlateNo,
VehicleType = a.VehicleType
}).FirstOrDefault();

Related

How to retrieve the data from mongodb in json format using c# entity framework

I am retrieving the data from mongodb.it is coming as bson document.
when i am converting it to json it throws system out of memory exception because of bulk data (>100 000) is coming from mongodb.
Is it possible to retrieve the data from mongodb in json format directly?
public object getFrequencyQuestionData1(int id)
{
var StudyId = (from ST in _context.Study_Team
where ST.Emp_Id == id
select (ST.Study_Id).ToString()).ToList();
var connectionString = "mongodb://localhost:27017";
MongoClient client = new MongoClient(connectionString);
MongoServer server = client.GetServer();
MongoDatabase db = server.GetDatabase("FormDataBase");
MongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument>("FrequencyQuestionForm");
var array = new BsonArray(StudyId.ToArray());
var query = Query.In("data.formList.IdentificationDetails.Study_Id", array);
var myLists = collection.Find(query);
myLists.SetFields(Fields.Include("_id","data.formList.IdentificationDetails.Study_Id", "data.formList.IdentificationDetails.Study_Name", "data.formList.IdentificationDetails.Volunteer_Id", "data.formList.IdentificationDetails.Form_Id","data.formList.IdentificationDetails.Form_Name", "data.formList.IdentificationDetails.Status", "data.formList.IdentificationDetails.Group_Id", "data.formList.IdentificationDetails.Visit_No","data.formList.IdentificationDetails.Created_Emp_Id", "data.formList.IdentificationDetails.Updated_Emp_Id"));
var items = myLists.ToList();
string document = items.ToJson();
JToken token = JToken.Parse(document);
var jObject = JObject.FromObject(new { formdata = token });
JArray sizes = (JArray)jObject["formdata"];
ArrayList SplittedData = new ArrayList();
for (int i = 0; i < sizes.Count(); i++)
{
JValue _id = (JValue)sizes[i]["_id"];
JObject sampledata = (JObject)sizes[i]["data"];
JArray sampledata2 = (JArray)sampledata["formList"];
JArray sampledata3 = (JArray)sampledata2[0]["IdentificationDetails"];
sampledata3[0]["id"] = _id;
int? Visit_No = (int?)sampledata3[0]["Visit_No"];
int? Group_Id = (int?)sampledata3[0]["Group_Id"];
int? Study_Id = (int?)sampledata3[0]["Study_Id"];
int? Form_Id = (int?)sampledata3[0]["Form_Id"];
int CreatedEmp_Id =(int)sampledata3[0]["Created_Emp_Id"];
var Visit_No1 = (from SS in _context.Study_Schedule
join SV in _context.Study_Visits
on new { SS.Study_Id, SS.Visit_No } equals
new { SV.Study_Id, SV.Visit_No }
//on SS.Study_Id equals SV.Study_Id && SS.Visit_No equals SV.Visit_No
where SS.Study_Id == Study_Id && SS.Visit_No == Visit_No && SS.Form_Id == Form_Id
select SV.Visit_Description).FirstOrDefault();
var Created_Emp_Id = (from US in _context.User
where US.Emp_Id == CreatedEmp_Id
select US.Emp_Name).FirstOrDefault();
sampledata3[0]["Created_Emp_Id"] = Created_Emp_Id;
if (Group_Id == null)
{
sampledata3[0]["Diet_Group"] = "";
}
else
{
var StudyGroup = (from SG in _context.Study_Group
where SG.Group_Id == Group_Id
select new
{
Group_Description = SG.Group_Description,
}).FirstOrDefault();
if (StudyGroup == null)
{
sampledata3[0]["Diet_Group"] = "";
}
else
{
sampledata3[0]["Diet_Group"] = StudyGroup.Group_Description.ToString();
}
}
sampledata3[0]["Visit"] = Visit_No1;
sampledata3[0]["Created_Emp_Id"] = Created_Emp_Id;
var sampledata4 = (JObject)sampledata3[0];
SplittedData.Add(sampledata4);
}
var jObject1 = JObject.FromObject(new { formdata = SplittedData});
return jObject1;
}

Linq-OrderByDescending doesn't work for me-ASP.net MVC

I want to order my list by idEtatD but this attribute isn't my table primarykey or id it's a normal attribute migrated from another table,nut OrderBy or OrderByDescending didn't give me a result my list still not ordered by idEtatD.
public ActionResult ListeDemande( int? page)
{
traçabilitérepository=new TraçabilitéDemandeRepository(db);
var listdemandes = (from d in db.Demande_Gabarit
join t in db.Traçabilité_Demande_Gabarit
on d.id_demande equals t.iddemande into ThisList
from t in ThisList.DefaultIfEmpty()
select new
{
id_demande=d.id_demande,
NumDemande = d.NumDemande,
Emetteur = d.Emetteur,
Date = d.Date,
Ligne = d.Ligne.designation,
Etat = t.Etat_Demande_Gabarit.EtatDemande
}).ToList().Select(x => new DemandeViewModel()
{
NumDemande = x.NumDemande,
Emetteur = x.Emetteur,
Date = x.Date,
designation = x.Ligne,
EtatDemande = x.Etat,
id_demande = x.id_demande
});
int pageSize = 10;
int pageNumber = (page ?? 1);
return View(listdemandes.OrderByDescending(x => x.idEtatD).ToList().ToPagedList(pageNumber, pageSize));
}
Please I need your help and thank you.
You can order the items at the beginning, but you need to include it in the list:
traçabilitérepository = new TraçabilitéDemandeRepository(db);
var listdemandes = (from d in db.Demande_Gabarit
join t in db.Traçabilité_Demande_Gabarit
on d.id_demande equals t.iddemande into ThisList
from t in ThisList.DefaultIfEmpty()
orderby t.idEtatD descending
select new
{
id_demande = d.id_demande,
NumDemande = d.NumDemande,
Emetteur = d.Emetteur,
Date = d.Date,
Ligne = d.Ligne.designation,
Etat = t.Etat_Demande_Gabarit.EtatDemande,
idEtatD = XXXX
}).ToList().Select(x => new DemandeViewModel()
{
NumDemande = x.NumDemande,
Emetteur = x.Emetteur,
Date = x.Date,
designation = x.Ligne,
EtatDemande = x.Etat,
id_demande = x.id_demande
});

Sorting multiple LINQ results of different models as one list in MVC

I am trying to sort a list of users that are either students, colleagues or guests and sort them in my view based on their names.
Here is the code:
public ActionResult Index()
{
var db = new PraktikumDataContext();
var model = new List<AdminUserListItem>();
var studs = (from stud in db.Students select new AdminUserListItem() {Name = stud.FH_Angehörige.Name, LastLogin = stud.FH_Angehörige.FE_Nutzer.Letzter_Login, Rolle = "Student"}).OrderBy(stud => stud.Name);
model.AddRange(studs);
var mits = (from mit in db.Mitarbeiters select new AdminUserListItem() {Name = mit.FH_Angehörige.Name, LastLogin = mit.FH_Angehörige.FE_Nutzer.Letzter_Login, Rolle = "Mitarbeiter"}).OrderBy(stud => stud.Name);
model.AddRange(mits);
var gasts = (from gast in db.Gasts select new AdminUserListItem() {Name = gast.Name, LastLogin = gast.FE_Nutzer.Letzter_Login, Rolle = "Gast"}).OrderBy(stud => stud.Name);
model.AddRange(gasts);
model = model.OrderByDescending()
return View(model);
}
What I've already done with OrderBy sorts each model in it's own scope, however since I have 3 models, I am a little bit confused now how to somehow make them to be seen as one list and then sort them and show them in my website.
Consider using a LINQ union that makes a single call to the server:
public ActionResult Index()
{
var db = new PraktikumDataContext();
var model =
(from stud in db.Students
select new AdminUserListItem()
{
Name = stud.FH_Angehörige.Name,
LastLogin = stud.FH_Angehörige.FE_Nutzer.Letzter_Login,
Rolle = "Student"}
).Union(
from mit in db.Mitarbeiters
select new AdminUserListItem()
{
Name = mit.FH_Angehörige.Name,
LastLogin = mit.FH_Angehörige.FE_Nutzer.Letzter_Login,
Rolle = "Mitarbeiter"}
).Union(
from gast in db.Gasts
select new AdminUserListItem()
{
Name = gast.FH_Angehörige.Name,
LastLogin = gast.FE_Nutzer.Letzter_Login,
Rolle = "Gast"}
)
.OrderByDescending(a => a.Name)
.ToList();
return View(model);
}

Populate a view model with a data model with a method aswell

i need to populate my articles ViewModel with a model that has the database data in it, but i have a method that i need to assign to one of my properties
The list of images is the property that needs the method on it.
The method is called once for every item in the list of articles.
Here is my code:
public ActionResult ArticleTypes(string at)
{
articleViewModel.Images = new List<ImageInfo>();
var query = (from a in db.Articles
where a.SelectedArticleType == at
select new ArticlesViewModel
{
Id = a.Id,
Body = a.Body,
Headline = a.Headline,
PostedDate = a.PostedDate,
SelectedArticleType = a.SelectedArticleType,
UserName = a.UserName,
}).ToList();
articleViewModel.Images = imageService.GetImagesForArticle(articlemodel.Id.ToString());
return View(query);
}
I have also tried putting the method inside the linq:
public ActionResult ArticleTypes(string at)
{
articleViewModel.Images = new List<ImageInfo>();
var query = (from a in db.Articles
where a.SelectedArticleType == at
select new ArticlesViewModel
{
Id = a.Id,
Body = a.Body,
Headline = a.Headline,
PostedDate = a.PostedDate,
SelectedArticleType = a.SelectedArticleType,
UserName = a.UserName,
Images = imageService.GetImagesForArticle(a.Id.ToString())
}).ToList();
return View(query);
}
it throws an exception of:
An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: LINQ to Entities does not recognize the method 'System.Collections.Generic.List`1[New_MinecraftNews_Webiste_MVC.Models.ImageInfo] GetImagesForArticle
I added a foreach loop at the end insted of anything else and it works:
public ActionResult ArticleTypes(string at)
{
articleViewModel.Images = new List<ImageInfo>();
var modelList = (from a in db.Articles
where a.SelectedArticleType == at
select new ArticlesViewModel
{
Id = a.Id,
Body = a.Body,
Headline = a.Headline,
PostedDate = a.PostedDate,
SelectedArticleType = a.SelectedArticleType,
UserName = a.UserName
}).ToList();
foreach (var model in modelList)
{
model.Images = imageService.GetImagesForArticle(model.Id.ToString());
}
return View(modelList);
}

Is there a way to combine 2 LINQ2XML queries?

var instructions = (from item in config.Elements("import")
select new
{
name = item.Attribute("name").Value,
watchFolder = item.Attribute("watchFolder").Value,
root = item.Element("documentRoot").Value,
DocumentNameDynamic = item.Element("documentName").Attribute("xpath").Value,
DocumentNameStatic = item.Element("documentName").Attribute("static").Value,
TemplateName = item.Element("template").Attribute("template").Value,
Path = item.Element("path").Attribute("path").Value,
fields = item.Element("fields").Elements()
}).SingleOrDefault();
var fields = from item in instructions.fields
select new
{
xpath = item.Attribute("xpath").Value,
FieldName = item.Attribute("FieldName").Value,
isMultiValue = bool.Parse(item.Attribute("multiValue").Value)
};
I think something like this should work. I added the Select method to return the anonymous class.
var instructions = (from item in config.Elements("import")
select new
{
name = item.Attribute("name").Value,
watchFolder = item.Attribute("watchFolder").Value,
root = item.Element("documentRoot").Value,
DocumentNameDynamic = item.Element("documentName").Attribute("xpath").Value,
DocumentNameStatic = item.Element("documentName").Attribute("static").Value,
TemplateName = item.Element("template").Attribute("template").Value,
Path = item.Element("path").Attribute("path").Value,
fields = item.Element("fields").Elements().Select(item => new {
xpath = item.Attribute("xpath").Value,
FieldName = item.Attribute("FieldName").Value,
isMultiValue = bool.Parse(item.Attribute("multiValue").Value)
}
).SingleOrDefault();
If you don't want to use the Select Extension method, you can use LINQ syntax. Here is an example of this.
var instructions = (from item in config.Elements("import")
select new
{
name = item.Attribute("name").Value,
watchFolder = item.Attribute("watchFolder").Value,
root = item.Element("documentRoot").Value,
DocumentNameDynamic = item.Element("documentName").Attribute("xpath").Value,
DocumentNameStatic = item.Element("documentName").Attribute("static").Value,
TemplateName = item.Element("template").Attribute("template").Value,
Path = item.Element("path").Attribute("path").Value,
fields = from e in item.Element("fields").Elements()
select new {
xpath = item.Attribute("xpath").Value,
FieldName = item.Attribute("FieldName").Value,
isMultiValue = bool.Parse(item.Attribute("multiValue").Value)
} // End of inner select statement
} // End of outer select statement
).SingleOrDefault();

Categories

Resources