Here is my Code :
string[] aa = new string[] { "Title", "Image", "Description" };
for (var i = 0; i <= 3; i++)
{
aa[i] = ems.SupportAdds.Where(x => x.ArticleId == id).Select(x => x.aa[i]).ToArray();
ViewBag.Collection[i] = aa[i];
}
I am getting error near x.aa[i].It is saying Table doesn't contain aa[i]. I want to use like that to short code. Please help me. I have its long version too which is working with my code.
Here is that one:
var Title = ems.SupportAdds.Where(x => x.ArticleId == id).Select(x => x.Title).ToArray();
ViewBag.Collection1 = Title;
var Description = ems.SupportAdds.Where(x => x.ArticleId == id).Select(x => x.Description).ToArray();
ViewBag.Collection2 = Description;
var Image = ems.SupportAdds.Where(x => x.ArticleId == id).Select(x => x.Image).ToArray();
ViewBag.Collection3 = Image;
And In view :
#Html.Raw(ViewBag.Collection2[i]
#Html.Raw(ViewBag.Collection2[i]
#Html.Raw(ViewBag.Collection3[i] // with increasing forloop which is working fine.
But I want to short it so I thought to use an array but it is not working with array. Can you guys suggest me the better way to write this code with lambda notation? Help will be appreciated.Thanks
I think you can improve performance by making changes like this
var allRecords= ems.SupportAdds.Where(x => x.ArticleId == id);
ViewBag.Collection1 = allRecords.Select(x => x.Title).ToArray();
ViewBag.Collection2 = allRecords.Select(x => x.Description).ToArray();
ViewBag.Collection3 = allRecords.Select(x => x.Image).ToArray();
Related
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I have a table of questions and a table of answers
I always need to display the list of questions regardless and there is a corresponsing asnwer, I need to grab that answer (response)
I use the following code
var Questions = db.Questions.Where(x => x.isActive);
var Answers = db.Answers.Where(x => x.AssessmentID == 99);
AssessmentResponseVM model = new AssessmentResponseVM();
foreach (var question in Questions)
{
AnswerAndQuestions q = new AnswerAndQuestions { };
q.QuestionText = question.QuestionText;
q.QuestionID = question.ID;
q.Response = Answers.Where(a => a.QuestionID == question.ID).SingleOrDefault().Response; <--- throws exception if there is no answer for the question
model.Questions.Add(q);
}
But get this error
Object reference not set to an instance of an object.
On this line
q.Response = Answers.Where(a => a.QuestionID == question.ID).SingleOrDefault().Response;
change
q.Response = Answers.Where(a => a.QuestionID == question.ID).SingleOrDefault().Response;
to this code
q.Response=Answers.Any(a=>a.QuestionID==question.ID)?Answers.firstOrDefault(a => a.QuestionID == question.ID).Response:new Response();
q.Response = Answers.Any(a => a.QuestionID == question.ID) ? Answers.Where(a => a.QuestionID == question.ID).FirstOrDefault().Response;
If you're allowed to use C# 6.0, I would suggest to try new null-conditional operator.
q.Response = Answers.Where(a => a.QuestionID == question.ID).SingleOrDefault()?.Response;
It returns null when Answers.Where(a => a.QuestionID == question.ID).SingleOrDefault() returns default value, which is null.
If you need something else, not null, you can use null-coalescing operator.
q.Response = Answers.Where(a => a.QuestionID == question.ID).SingleOrDefault()?.Response ?? response, what you need;
Environment: EF6 code first
I have two tables e.g user and activity which have a many-to-many relation.
I want to know whether any user's activity has a given key, using Entity Framework in an asp.net mvc application.
is the following query performance wise?
is there any other way to write this query?
Query:
var userEntity = _dbcontext.Users.Find(userId);
var isAvailable = _dbcontext.Entry(userEntity)
.Collection(e => e.Activities)
.Query().Any(e => e.Name== "givenname");
updated:
i ran those queries and here are the time to run:
1
var userEntity = _dbcontext.Users.Find(userId);
var isAvailable = userEntity.Activities.Any(a => a.Name == "givenname");
time: 5.39s + time to fetch user
2
var isAvailable =_dbcontext.Users.Include(e => e.Activities)
.Any( u => u.UserId == userId
&& u.Activities.Any(a => a.Name == "givenname")
);
time: 5.73s
3
var userEntity = _dbcontext.Users.Find(userId);
var isAvailable = _dbcontext.Entry(userEntity)
.Collection(e => e.Activities)
.Query().Any(e => e.Name== "givenname");
time: 5.95s + time to fetch user
so it seems that choosing the second form of query be reasonable.
You can also try this:
var isAvailable =_dbcontext.Users.Include(e => e.Activities)
.Any( u => u.UserId == userId
&& u.Activities.Any(a => a.Name == "givenname")
);
If you haven't disabled lazy loading, then you don't need to call the Include extension method.
I would simplify this to:
var userEntity = _dbcontext.Users.Find(userId);
var isAvailable = userEntity.Activities.Any(a => a.Name == "givenname");
or maybe (I'm not quite clear what you're trying to achieve, from your question) - this doesn't take the userId into account, it just searches for any users that has any activity with that givenname:
var isAvailable = _dbcontext.Users.Any(u => u.Activities.Any(a => a.Name == "givenname"));
Single trip to the DB:
var result = _dbcontext.Users.Where( u => u.UserId == userId )
.Select( u => new {
User = u, // optional
IsAvailable = u.Activities.Any( a => a.Name == "givenname" )
} )
.SingleOrDefault();
I am using entityframework in my project.
I have 3 tables which are navigated with many to many relationship.
This is my diagram.
I want to select all my counters id which have last approve status == 15.
I wrote query like this;
var sayacOnayDurumlari =
db.CounterApproveStatus
.Where(x => x.ApproveStatusId == 15).OrderByDescending(x=>x.Id)
.GroupBy(x => x.CountersId)
.Select(e => e.FirstOrDefault());
but it takes my older records which are ID == 15
var son =
db.Counters.Where(
x => x.CounterApproveStatus.OrderByDescending(t => t.Id).FirstOrDefault().ApproveStatusId == 15)
.ToList();
I tried this and I supposed I achieved it. Is it a good query?
You need group first, then find if the latest Id in that group has desired statusId.
Following syntax may not be exactly right, but you could get idea.
var sayacOnayDurumlari =
db.CounterApproveStatus
.GroupBy(x => x.CountersId)
.Select(g => new {
CountersId = g.Key,
LatestRecord = g.OrderByDescending(x=> x.Id)
.FirstOrDefault()
})
.Where(g=> g.LatestRecord.ApproveStatusId == 15)
.Select(g => g.CountersId).ToList();
I have advertisement table, i want to order it first by special, then order by last added, but special ads has end date, so i want to order special ads that its date is still
This is my code
List<S_Advertisements> moduleItems = db.S_Advertisements
.Include(x => x.S_AdvertisementsImages)
.Where(x => x.CatId == pureId && x.IsActive == true)
.OrderByDescending(x => x.IsSpecial)
.ThenByDescending(x => x.AdId).ToList();
I want to know if Entity Framework will let me do something like that :
List<S_Advertisements> moduleItems = db.S_Advertisements
.Include(x => x.S_AdvertisementsImages)
.Where(x => x.CatId == pureId && x.IsActive == true)
.OrderByDescending(x => x.IsSpecial.Where(x => x.DateSpecialEnd > DateTime.Now))
.ThenByDescending(x => x.AdId).ToList();
may be :
DateTime dtn = Datetime.Now;
var moduleItems = db.S_Advertisements
.Include(x => x.S_AdvertisementsImages)
.Where(x => x.CatId == pureId && x.IsActive == true)
.Select( x => new {
o = x,
c = x.DateSpecialEnd > dtn ? 0 : 1 // not a boolean but an order info
})
.OrderByDescending(z => z.c)
.ThenByDescending(z => z.o.AdId).ToList();
same as in sql: view for calculating the field, then order the view.
The placement of the where clause doesn't affect ordering. Whether you order by IsSpecial or by IsSpecial.Where(...) the order would be the same, regardless. That's pretty much why what you're looking for doesn't exist: there's no need for it to.
I'm using sfWidgetFormDoctrineChoice to build select elements in a form. This is how I'm using:
// Fill maquinaemisorid
$this->widgetSchema['maquinaemisorid'] = new sfWidgetFormDoctrineChoice(array('model' => 'SdrivingMaquina', 'add_empty' => 'Seleccione una Máquina', 'table_method' => 'fillChoice'));
// Fill idoperador
$this->widgetSchema['idoperador'] = new sfWidgetFormDoctrineChoice(array('model' => 'SdrivingOperador', 'add_empty' => 'Seleccione un Operador', 'table_method' => 'fillChoice'));
// Fill idturno
$this->widgetSchema['idturno'] = new sfWidgetFormDoctrineChoice(array('model' => 'SdrivingTurno', 'add_empty' => 'Seleccione un Turno', 'table_method' => 'fillChoice'));
For the first widget all is fine and values are taken from DB as should be but for the second one and the third is not working. As you may notice I'm calling a method fillChoice in all widgets table_method. This is the code for the three:
SdrivingMaquinaTable.class.php
public function fillChoice() {
$id_empresa = sfContext::getInstance()->getUser()->getGuardUser()->getSfGuardUserProfile()->getIdempresa();
return Doctrine_Core::getTable('SdrivingMaquina')->createQuery('a')->where('a.idempresa = ?', $id_empresa)->execute();
}
SdrivingOperadorTable.class.php
public function fillChoice() {
$id_empresa = sfContext::getInstance()->getUser()->getGuardUser()->getSfGuardUserProfile()->getIdempresa();
return Doctrine_Core::getTable('SdrivingOperador')->createQuery('a')->where('a.idempresa = ?', $id_empresa)->execute();
}
SdrivingTurno.class.php
public function fillChoice() {
$id_empresa = sfContext::getInstance()->getUser()->getGuardUser()->getSfGuardUserProfile()->getIdempresa();
return Doctrine_Core::getTable('SdrivingTurno')->createQuery('a')->where('a.idempresa = ?', $id_empresa)->execute();
}
The method is the same always just changes the table used for each class. I check the generated queries and all are fine and if I run each on phpMyAdmin for example more than one value is fetched altough in idoperador and idturno just the latest is rendered. This is a very rare behavior and I can't find the error or mistake so I need some help or advice here.
As an adition I tried this in SdrivingRegistrosEmisoresForm.class.php (this is where the widgets are being generated):
$id_empresa = $this->current_user->getSfGuardUserProfile()->getIdempresa();
$choices_operador = Doctrine_Core::getTable('SdrivingOperador')->createQuery('a')->where('a.idempresa = ?', $id_empresa)->execute();
$this->widgetSchema['idoperador'] = new sfWidgetFormSelect(array('choices' => $choices_operador));
And this way works fine but the id for each item fetched isn't right meaning:
id item real_id
0 Item1 2
1 Item2 16
2 Item4 3
I talked about this in this topic but didn't get any answer, any help?
As stated in sfWidgetFormDoctrineChoice, if option *table_method* returns a collection like your methods, it renders choices with options *key_method* and method. By default , they are respectively getPrimaryKey() and *__toString()*.
Can we check you schema.yml and the __toString() ?
As for your last example the option choices of sfWidgetFormSelect should be an array an not a *Doctrine_Collection*