public class PowerPlantsBudgetUsage
{
public int PowerPlantID { get; set; }
public int TotalWork { get; set; }
public int ElectricalWorkNo { get; set; }
public int MechanicalWorkNo { get; set; }
public int CivilWorkNo { get; set; }
public int AdminWorkNo { get; set; }
public int VehicleWorkNo { get; set; }
[DisplayFormat(DataFormatString = "{0:N}")]
public decimal Total { get; set; }
public List<string> PowerPlantNameList { get; set; }
}
public IActionResult Total()
{
var query = _context.REHPData.Include(r => r.PowerPlants).Include(r => r.WorkCategories).GroupBy(r => r.PowerPlantID).Select(s => new PowerPlantsBudgetUsage
{
PowerPlantID = s.Key,
TotalWork = s.Count(),
ElectricalWorkNo = s.Count(x => x.WorkCategoriesID == 1),
MechanicalWorkNo = s.Count(x => x.WorkCategoriesID == 2),
CivilWorkNo = s.Count(x => x.WorkCategoriesID == 3),
AdminWorkNo=s.Count(x=>x.WorkCategoriesID==4),
VehicleWorkNo=s.Count(x=>x.WorkCategoriesID==6),
Total = s.Sum(x => x.ApprovedAmount),
PowerPlantNameList = s.Select(x => x.PowerPlants.PowerPlantName).ToList()
}).ToList();
return View(query);
[enter image description here][1]
}
my problems is PowerPlantNameList is show Totalwork count number
example totalwork is 5
powrplantname is test test test test test so on...
My View Result is Look like this
If i understand well you want to display only first PowerPlantName in your colmun. So change the property PowerPlantNameList to :
public string PowerPlantName { get; set; }
And affect it with :
[...]
Total = s.Sum(x => x.ApprovedAmount),
PowerPlantName = s.Select(p => p.PowerPlants.PowerPlantName).First()
Related
I have a problem. I cannot save cards without duplicates.
I have 3 tables a Deck, Card table and a CardDeck table which is the junction table.
The goal is to store a deck in the database without the cards being duplicated.
Table Card
namespace MTG_Deck.Models
{
public class Card
{
[Key]
public int CardId { get; set; }
public string Name { get; set; }
public string Text { get; set; }
public string Type { get; set; }
public string SetName { get; set; }
public string Artist { get; set; }
public string ManaCost { get; set; }
public string Rarity { get; set; }
public string ImageUrl { get; set; }
public string Toughness { get; set; }
public string Power { get; set; }
public string id { get; set; }
public virtual ICollection<DeckCard> Decks { get; set; }
}
}
Table Deck
namespace MTG_Deck.Models
{
public class Deck
{
[Key]
public int DeckId { get; set; }
[Required]
public string Name { get; set; }
[DataType(DataType.Date)]
public DateTime CreateAt { get; set; }
public User User { get; set; }
public virtual ICollection<DeckCard> Cards { get; set; }
}
}
Table CardDeck
namespace MTG_Deck.Models
{
public class DeckCard
{
public int DeckID { get; set; }
public int CardID { get; set; }
public Deck Deck { get; set; }
public Card Card { get; set; }
}
}
CardDeckRequest contains the content of the request.
namespace MTG_Deck.Models
{
public class CardDeckRequest
{
[Required]
public int UserID { get; set; }
[Required]
public string Token { get; set; }
[Required]
public Deck Deck { get; set; }
[Required]
[MinLength(5, ErrorMessage = "The deck must contain 60 cards.")]
public List<Card> Cards { get; set; }
}
}
Controller
[HttpPost]
public IActionResult Add([FromBody] CardDeckRequest request)
{
User user = _context.User.Where(u => u.Token == request.Token).FirstOrDefault<User>();
if (user == null) {
var error = new string[] {"You have to be connected to create a deck!"};
BadRequest(new { errors = new { success = error } });
}
List<DeckCard> deckList = new List<DeckCard>();
if (ModelState.IsValid) {
request.Deck.User = user;
foreach (var item in request.Cards)
{
Card card = _context.Card.FirstOrDefault(c => c.Name == item.Name);
if (card == null) {
card = item;
Console.WriteLine("coucou");
}
DeckCard deckCard = new DeckCard {
Card = card,
Deck = request.Deck
};
deckList.Add(deckCard);
}
_context.DeckCard.AddRange(deckList);
_context.SaveChanges();
var error = new string[] {"Your deck has been successfully saved."};
return Ok(new { errors = new { success = error } });
}
return BadRequest(ModelState.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
));
}
I have this models:
public class AudienceInfo
{
public int Id { get; set; }
public string Departments { get; set; }
public List<CountOfDestination> CountOfDestinations { get; set; }
}
public sealed class CountOfDestination
{
public string DestinationName { get; set; }
public int? CountRoom { get; set; }
public int? CountOfFiles { get; set; }
}
And this table in DB.
public class AudienceInfo : IModelWithId
{
public int Id { get; set; }
....
public RoomPurpose RoomPurpose { get; set; }
public List<AudienceInfo_File> Files { get; set; }
}
After selecting the "Departments" (where condition), I get a list of data. Then, I GroupBy "RoomPurpose" and get
"CountRoom" for every row = DestinationName. This part work correctly.
Also, i need to get the CountOfFiles ... don't know how to do this
return dbAudInfo
.Where(x => x.RightOfPreferentialUse.Id == Id)
.Select(x => new AudienceInfo
{
Departments = x.RightOfPreferentialUse.Name,
Date = date1,
CountOfDestinations = dbAudInfo
.GroupBy(z => new { z.RoomPurpose })
.Select(y => new CountOfDestination
{
DestinationName = y.Key.RoomPurpose.Name,
CountRoom = y.Count(z => z.RightOfPreferentialUse.Id == Id),
CountOfFiles = ?????????????????????????
}).ToList()
}).FirstOrDefaultAsync();
How can i connect a list in LINQ query with GroupBy.
Also, i need to get the CountOfFiles ... don't know how to do this
Use:
CountOfFiles = y.ToList().First(a => a.Id == y.Id).Files.Count()
How can i connect a list in LINQ query with GroupBy.
Can you elaborate?
I have a bunch of classes with some data:
public class Teacher
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime bDate { get; set; }
//One-to-one with course
public int CourseId { get; set; }
public virtual Course Course { get; set; }
}
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection <Student_Course> Student_Courses { get; set; }
public int TeacherId { get; set; }
public virtual Teacher Teacher { get; set; }
}
public class Grade
{
public int Id { get; set; }
public int Mark { get; set; }
//one-to-many with Student_Course
public int Student_CourseId { get; set; }
public Student_Course Student_Course { get; set; }
}
public class Student_Course
{
public int Id { get; set; }
//many-to-many with student
public int StudentId { get; set; }
public virtual Student Student { get; set; }
//many-to-many with course
public int CourseId { get; set; }
public virtual Course Course { get; set; }
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime bDate { get; set; }
//one-to-many with student_course
public virtual ICollection <Student_Course> Student_Courses { get; set; }
}
Now i trying to write a query - for everyone teacher(name) needs to output his best student(name) by student mark, and the best mark, from class Grades, my code:
public IActionResult Task9()
{
var task9 = Db.Grades.GroupBy(gr => gr.Student_Course.Course.Teacher.Name).Select(x => new Task9
{
NameOfSt = x.Select(st => st.Student_Course.Student.Name).FirstOrDefault(),//Needs to correct this line
NameOfTeac = x.Select(r => r.Student_Course.Course.Teacher.Name).FirstOrDefault(),
BestMark = x.Max(gr => gr.Mark)
//NameOfSt = Db.Students.FirstOrDefault(st => st.Id ==x.FirstOrDefault().Student_Course.StudentId).Name
});
return View(task9);
}
So that code output correct teacher name and best mark on the course from students. But the student name is actually wrong. How can i fix that? Thanks for any help.
Teac
BestMark
NameStud
You could use OrderByDescending by Mark before select student name:
var task9 = Db.Grades.GroupBy(gr => gr.Student_Course.Course.Teacher.Name).Select(x => new Task9
{
NameOfSt = x.OrderByDescending(st => st.Mark).Select(st => st.Student_Course.Student.Name).FirstOrDefault(),//Needs to correct this line
NameOfTeac = x.Select(r => r.Student_Course.Course.Teacher.Name).FirstOrDefault(),
BestMark = x.Max(gr => gr.Mark)
});
Within the GroupBy you need to use the value of the grouping (in this case x) to select the Grade object with the highest Grade. In the code below, I get the bestGrade object by ordering by the Mark in descending order and then taking the first entry and then I take the student, name and best mark from that object:
public IActionResult Task9()
{
var task9 = Db.Grades.GroupBy(gr => gr.Student_Course.Course.Teacher.Name).Select(x =>
{
var bestGrade = x.OrderByDescending(y => y.Mark).First();
return new Task9
{
NameOfSt = bestGrade.Student_Course.Student.Name,//Needs to correct this line
NameOfTeac = bestGrade.Student_Course.Course.Teacher.Name,
BestMark = bestGrade.Mark
};
});
return View(task9);
}
I am facing a problem in EF6. When I execute the query Select it return the value. But when I add Select it returns null.
The code is here:
The (W) is not null here...
var list = db.X.Include("Y").Include("Z.W")
.OrderBy(c => c.Id)
.Skip(pageSize * page)
.Take(pageSize)
.ToList();
Here, The W value is null...
var list = db.X.Include("Y").Include("Z.W")
.Select(a => new { a.Id, a.Z})
.OrderBy(c => c.Id)
.Skip(pageSize * page)
.Take(pageSize)
.ToList();
Please help :)
UPDATE 1
public class academy
{
public int Id { get; set; }
[StringLength(255)]
[Index(IsUnique = true)]
public string Name { get; set; }
public string Logo { get; set; }
[Required]
public Owner owner { get; set; }
public List<location> Location { get; set; }
}
public class location
{
public int Id { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string Neighborhood { get; set; }
public string Street { get; set; }
public academy Academy { get; set; }
public List<stadium> Stadiums { get; set; }
public List<Administrators> Administrators { get; set; }
public List<addition> Addition { get; set; }
public List<Pricing> Pricing { get; set; }
public List<time_frame> TimeFrames { get; set; }
[NotMapped]
public string Details {
get { return (City + " - " + Street); }
}
}
public class Pricing
{
public int Id { get; set; }
public double Price { get; set; }
public double? PriceAfterOffer { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public location Location { get; set; }
public players_capacity StadiumCapacity { get; set; }
}
public class players_capacity
{
public int Id { get; set; }
[StringLength(255)]
[Index(IsUnique = true)]
public string Capacity { get; set; }
}
var list = db.locations
.Select(a => new { a.Id, a.City, a.Region, a.Street, a.Latitude, a.Longitude, a.Pricing, a.Academy })
.OrderBy(c => c.Id)
.Skip(pageSize * page)
.Take(pageSize)
.ToList();
The problem is on players_capacity always null
Any additional data specified by Include is ignored if the query changes "shape", in this case your additional .Select expression invalidates the previous Include terms so they are ignored. The same happens if you do a GroupBy or GroupJoin.
Fortunately the fix is simple: explicitly specify the Y and Z.W members in your projection:
var list = db.X
.Select( x => new { x.Id, x.Z, x.Y, x.Z.W } )
.OrderBy( p => p.Id )
.Skip( () => pageSize * page )
.Take( () => pageSize )
.ToList();
(Note that I'm using the Expression<> overloads of Skip and Take, as those are better for use with EF).
I'm trying to get sum of all items of cars. But i'm just getting sum of each items, which you can see here Link
So how can I get sum of all items, like the sum is (4), instead of getting each items?
Controller:
public ActionResult Home()
{
var model = new CompositeModel();
model.CountCars = getCountOfCars();
return View(model);
}
private IEnumerable<CountCarsrCountView> getCountOfCars()
{
var countCars = this.Data.Cars.All()
.Select(t => new CountCarsrCountView
{
counter = t.Cars.Count()
});
return countCars ;
}
ViewModel
public class CountCarsViewModel
{
public int counter { get; set; }
}
CompositeModel
public class CompositeModel
{
public IEnumerable<CountCarsViewModel> CountCars { get; set; }
}
View
#model CompositeModel
<div class="container">
#for (int i = 0; i < Model.CountCarsViewModel.Count(); i++)
{
var cars = Model.CountCarsViewModel.ElementAt(i);
<p>#cars.counter</p>
}
</div>
Car model:
public class Car
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int Price { get; set; }
public virtual Category Category { get; set; }
public int CategoryId { get; set; }
public int FilePathId { get; set; }
public string FileName { get; set; }
public string UserId { get; set; }
public virtual User Users { get; set; }
}
You can use Linq as so:
public class MyItem
{
public int MyCount { get; set; }
}
public List<MyItem> AllItems { get; set; }
In this example if you want the count of all items in the list you would do this:
var count = AllItems.Count();
If you wanted to sum the Counts of all items in the list you would do this:
var count2 = AllItems.Sum(a => a.MyCount);
Example:
AllItems = new List<UserQuery.MyItem>()
{
new MyItem(){ MyCount = 3 },
new MyItem(){ MyCount = 4 },
};
var count = AllItems.Count(); // This would be 2
var count2 = AllItems.Sum(a => a.MyCount); // This would be 7