MVC3 - Sorting db query when using Include - asp.net-mvc

I'm doing a site where i've been using the MvcMusicStore as a base.
I want to get all the albums from a specific genre, and order these by Artist name. I can't really figure out how to order by Artist name.
My models:
public partial class Genre
{
public int GenreId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public ICollection Albums { get; set; }
public ICollection Artists { get; set; }
}
public class Artist
{
public int ArtistId { get; set; }
public string Name { get; set; }
}
public class Album
{
public int AlbumId { get; set; }
public int GenreId { get; set; }
public int ArtistId { get; set; }
public string Title { get; set; }
public string Price { get; set; }
public string AlbumArtUrl { get; set; }
public string Description { get; set; }
public virtual Genre Genre { get; set; }
public virtual Artist Artist { get; set; }
}
My Controller:
public ActionResult Index(string genre = "CD/LP")
{
var genreModel = storeDb.Genres.Include("Albums").Include("Artists")
.Where(g => g.Name == genre).FirstOrDefault();
return View(genreModel);
}
How can I order the results by Artist name?

storeDb.Albums.Where(a => a.Genre.Name == genre).OrerBy(a => a.Artist.Name)

Related

Foregin key relationship error

I have following model classes
Each Item has 4 languages in perticular languages table
public class Item
{
[Key]
public int Id { get; set; }
public DateTime? ExpireDate { get; set; }
}
public class ItemLanguage
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("Language")]
public int LanguageId { get; set; }
[ForeignKey("Item")]
public int ItemId { get; set; }
public Language Language { get; set; }
public Item Item { get; set; }
}
Each item library has 4 languages in perticular language table
public class ItemLibrary
{
[Key]
public int Id { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd MMM yyyy}")]
public DateTime? ExpireDate { get; set; }
}
public class ItemLibraryLanguage
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[ForeignKey("Language")]
public int LanguageId { get; set; }
[ForeignKey("ItemLibrary")]
public int ItemLibraryId { get; set; }
public ItemLibrary ItemLibrary { get; set; }
public Language Language { get; set; }
}
Now I want to add items to the ItemLibraryItems table.
It need to save the ItemId and the ItemLibraryId in this table(Not the languageId). When displaying the selected items for the library it needs to show the according to the selected language in login.
public class ItemLibraryItem
{
[Key]
public int Id { get; set; }
[ForeignKey("ItemLibrary")]
public int ItemLibraryId { get; set; }
[ForeignKey("Item")]
public int ItemId { get; set; }
public ItemLibrary ItemLibrary { get; set; }
public Item Item { get; set; }
}
But when I'm trying to create the Controller by using ItemLibraryItem as the model class it gives the error
The entity types 'ItemLibraryItem' and 'ItemLibraryLanguage' cannot share table 'ItemLibraryLanguages' because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary keys between them.

mvc model with a foreign key, connection lost

I have 2 models, Artist and Album.
Artist have a collection of albums.
Album have a foreigm key to Artist (int artistId).
Now in my site you get to select the album for edition from its artist,
and when I send the album back to the controller, its artistId always 0 (default value of int) and I failed to save the album, because there is no such artist with 0 id. How I'm losing the id of the artist?
the artist
public class Artist
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string NickName { get; set; }
public string Website { get; set; }
public string Facebook { get; set; }
public string Twitter { get; set; }
public string Wikipedia { get; set; }
public string Background { get; set; }
public long StartYearActivity { get; set; }
public virtual ICollection<Album> Albums { get; set; }
public DateTime Birthdate { get; set; }
}
the album
public class Album
{
public int Id { get; set; }
public int ArtistId { get; set; }
public string Genre { get; set; }
public string Wikipedia { get; set; }
public List<Song> Songs { get; set; }
public string Name { get; set; }
public int NumOfSongs { get { return this.Songs != null ? this.Songs.Count : 0; } }
public int Year { get; set; }
}
the save method for album when the artist id is null:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditAlbum([Bind(Include = "Id,Genre,Wikipedia,Name,Year")] Album album)
{
db.Entry(album).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(album);
}
What am I doing wrong?

Display list of data on the basis of roles in MVC asp.net identity

I have a list which shows all the videos uploaded by Admin and Users, But I want to apply some condition to individually display User and Admin uploads list (just want to separate list on the basis of roles).
How can i do it?
This is the code which displays all the Videos
public ActionResult Index()
{
var videos = db.Videos.Include(v => v.Artist).Include(v => v.Category);
return View(videos.ToList());
}
Here is the video class
public class Video
{
public int Id { get; set; }
public virtual Category Category { get; set; }
public int CategoryId { get; set; }
public virtual Artist Artist { get; set; }
public int ArtistId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Length { get; set; }
public string Keywords { get; set; }
public string format { get; set; }
public string Language { get; set; }
public string URL { get; set; }
public string Image { get; set; }
public string UserId { get; set; }
public bool isblock { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public virtual ICollection<Comment> comments { get; set; }
public virtual ICollection<Like> likes { get; set; }
public virtual ICollection<HitCounter> Views { get; set; }
}

ASP.NET MVC finding pending fees

I'm learning ASP.NET MVC 4 with Entity Framework (Database First) and ran into a problem that I'm not able to solve.
I have following tables:
Student: To store students information
Course: To store courses running in an institute
StudentCourse: To store which student selected what course
Fees: To store submitted fees by a student corresponding to StudentCourse
Now, I wan't to show course name, course fees, total fees submitted & the pending fees of students
I'm using Entity Framework in the project and trying to execute a query like this:
var feeslist = entities.Fees
.Where(m => m.StudentCourse.status=="pending")
.GroupBy(m => m.StudentCourse.id)
.Select(m => new { StudentCourseId = m.Key, SumOfFees = m.Sum(v => v.fees) });
I want to get Course object instead of StudentCourseId so that i can display the course, its course fees and total fees submitted by student.
In case, I'm listing all of the four class contents:
Student
public partial class Student
{
public Student()
{
this.Leaves = new HashSet<Leave>();
this.StudentCourses = new HashSet<StudentCourse>();
}
public int id { get; set; }
public string first_name { get; set; }
public string middle_name { get; set; }
public string last_name { get; set; }
public string password { get; set; }
public string email { get; set; }
public string gender { get; set; }
public string facebook { get; set; }
public string contact_number { get; set; }
public string address { get; set; }
public string admin { get; set; }
public string college { get; set; }
public string status { get; set; }
public System.DateTime createdat { get; set; }
public System.DateTime updatedat { get; set; }
public string descripton { get; set; }
public virtual ICollection<Leave> Leaves { get; set; }
public virtual ICollection<StudentCourse> StudentCourses { get; set; }
}
Course
public partial class Course
{
public Course()
{
this.CourseContents = new HashSet<CourseContent>();
this.StudentCourses = new HashSet<StudentCourse>();
}
public int id { get; set; }
public string course_name { get; set; }
public int course_fees { get; set; }
public int duration { get; set; }
public string admin { get; set; }
public string status { get; set; }
public System.DateTime createdat { get; set; }
public System.DateTime updatedat { get; set; }
public virtual ICollection<CourseContent> CourseContents { get; set; }
public virtual ICollection<StudentCourse> StudentCourses { get; set; }
}
StudentCourse
public partial class StudentCourse
{
public StudentCourse()
{
this.Fees1 = new HashSet<Fee>();
this.Issues = new HashSet<Issue>();
}
public int id { get; set; }
public int student_id { get; set; }
public int course_id { get; set; }
public int fees { get; set; }
public System.DateTime join_date { get; set; }
public string admin { get; set; }
public System.DateTime createdat { get; set; }
public System.DateTime updatedat { get; set; }
public string status { get; set; }
public virtual Course Course { get; set; }
public virtual ICollection<Fee> Fees1 { get; set; }
public virtual ICollection<Issue> Issues { get; set; }
public virtual Student Student { get; set; }
}
Fee
public partial class Fee
{
public int id { get; set; }
public int student_course_id { get; set; }
public int fees { get; set; }
public string admin { get; set; }
public System.DateTime createdat { get; set; }
public System.DateTime updatedat { get; set; }
public virtual StudentCourse StudentCourse { get; set; }
}
var feeslist = entities.Fees
.Where(m => m.StudentCourse.status=="pending")
.GroupBy(m => m.StudentCourse.Course)
.Select(m => new { Course = m.Key, SumOfFees = m.Sum(v => v.fees) });

EF Many to Many Relationship on 3 Tables(Fluent API)

I have 3 tables that needs to be combined in one table. On below you can see the codes.
The problem is each player could play on one or more team on each tournament. Players and teams arranger by every new tournament.
So how can i map it with fluent api or maybe there is a better way to solve it. Thanks from now on.
public class Player
{
public int PlayerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public DateTime TimeStamp { get; set; }
public ICollection<Team> Teams { get; set; }
public ICollection<Tournament> Tournaments { get; set; }
}
public class Team
{
public int TeamID { get; set; }
public string Name { get; set; }
public DateTime TimeStamp { get; set; }
public ICollection<Player> Players { get; set; }
public ICollection<Tournament> Tournaments { get; set; }
}
public class Tournament
{
public int TournamentID { get; set; }
public DateTime Date { get; set; }
public int PlaceID { get; set; }
public DateTime TimeStamp { get; set; }
public virtual Place Place { get; set; }
public ICollection<Player> Players { get; set; }
public ICollection<Team> Teams { get; set; }
}
public class BPContext : DbContext
{
public DbSet<Tournament> Tournaments { get; set; }
public DbSet<Place> Places { get; set; }
public DbSet<Table> Tables { get; set; }
public DbSet<Player> Players { get; set; }
public DbSet<Team> Teams { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
I don't see what are you trying to accomplish with this. You have tables that contain all players, all teams and all tournaments.
I suppose there will be a match to be played? What you can do is create another table Matches, to use entity similar to this:
public class Match
{
[Key]
public int MatchId {get;set;}
[ForeignKey("Tournament")]
public int TournamentId {get;set;}
[InverseProperty("Matches")]
public virtual List<Team> Teams {get;set;}
[InverseProperty("Matches")]
public virtual List<Player> Players {get;set;}
[InverseProperty("Matches")]
public virtual Tournament Tournament {get;set;}
}
This new entity holds all 3 previous entities. However you have to modify previous ones to include these changes:
public class Player
{
public int PlayerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public DateTime TimeStamp { get; set; }
[InverseProperty("Players")]
public virtual List<Match> Matches { get; set; }
[InverseProperty("Players")]
public virtual List<Team> Teams {get;set;}
}
Getting all tournaments for player can be done with LINQ : ctx.Players.Where(x => x.PlayerId == 15).Matches.Select(x => x.TournamentId).
If you want to see all the players in a tournament: ctx.Matches.Where(x => x.TournamentId ==15).Players.Select(x => x.Name).
public class Team
{
public int TeamID { get; set; }
public string Name { get; set; }
public DateTime TimeStamp { get; set; }
[InverseProperty("Teams")]
public List<Match> Matches {get;set;}
[InverseProperty("Teams")]
public List<Player> Players {get;set;}
}
public class Tournament
{
public int TournamentID { get; set; }
public DateTime Date { get; set; }
public int PlaceID { get; set; }
public DateTime TimeStamp { get; set; }
public virtual Place Place { get; set; }
[InverseProperty("Tournament")]
public virtual List<Match> Matches {get;set;}
}

Resources