2.model: 2.1 Album
2.model: 2.1 Album
Model
2.1 Album
using using using using System.ComponentModel; System.ComponentModel.DataAnnotations; System.Web.Mvc; System.Collections.Generic;
namespace MvcMusicStore.Models { [Bind(Exclude = "AlbumId")] public class Album { [ScaffoldColumn(false)] public int AlbumId { get; set; } [DisplayName("Genre")] public int GenreId { get; set; } [DisplayName("Artist")] public int ArtistId { get; set; } [Required(ErrorMessage = "An Album Title is required")] [StringLength(160)] public string Title { get; set; } [Required(ErrorMessage = "Price is required")] [Range(0.01, 100.00, ErrorMessage = "Price must be between 0.01 and 100.00")] public decimal Price { get; set; } [DisplayName("Album Art URL")] [StringLength(1024)] public string AlbumArtUrl { get; set; } public virtual Genre Genre { get; set; } public virtual Artist Artist { get; set; } public virtual List<OrderDetail> OrderDetails { get; set; } }
2.2 Artist
namespace MvcMusicStore.Models { public class Artist { public int ArtistId { get; set; } public string Name { get; set; } } }
2.3 Genre
using System.Collections.Generic; namespace MvcMusicStore.Models { public partial class Genre { public int GenreId { get; public string Name { get; public string Description public List<Album> Albums } }
2.4 MusicStoreEntities
using System.Data.Entity; namespace MvcMusicStore.Models { public class MusicStoreEntities : DbContext { public DbSet<Album> Albums { get; set; } public DbSet<Genre> Genres { get; set; } public DbSet<Artist> Artists { get; set; } public DbSet<Cart> Carts { get; set; }
public DbSet<Order> Orders { get; set; } public DbSet<OrderDetail> OrderDetails { get; set; } } }
2.5 SampleData
using using using using using System; System.Collections.Generic; System.Linq; System.Web; System.Data.Entity;
namespace MvcMusicStore.Models { public class SampleData : DropCreateDatabaseIfModelChanges<MusicStoreEntities> { protected override void Seed(MusicStoreEntities context) { var genres = new List<Genre> { new Genre { Name = "Rock" }, new Genre { Name = "Jazz" }, new Genre { Name = "Metal" }, new Genre { Name = "Alternative" }, new Genre { Name = "Disco" }, new Genre { Name = "Blues" }, new Genre { Name = "Latin" }, new Genre { Name = "Reggae" }, new Genre { Name = "Pop" }, new Genre { Name = "Classical" } }; var artists = new List<Artist> { new Artist { Name = "Aaron Copland & London Symphony Orchestra" }, new Artist { Name = "Aaron Goldberg" }, new Artist { Name = "AC/DC" }, new Artist { Name = "Accept" },
new Artist { Name = "Adrian Leaper & Doreen de Feis" }, new Artist { Name = "Aerosmith" }, new Artist { Name = "Zeca Pagodinho" } }; new List<Album> { new Album { Title = "The Best Of Men At Work", Genre = genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = artists.Single(a => a.Name == "Men At Work"), AlbumArtUrl = "/Content/Images/placeholder.gif" }, new Album { Title = "New Adventures In Hi-Fi", Genre = genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = artists.Single(a => a.Name == "R.E.M."), AlbumArtUrl = "/Content/Images/placeholder.gif" }, new Album { Title = "Raul Seixas", Genre = genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = artists.Single(a => a.Name == "Raul Seixas"), AlbumArtUrl = "/Content/Images/placeholder.gif" }, new Album { Title = "Ao Vivo [IMPORT]", Genre = genres.Single(g => g.Name == "Latin"), Price = 8.99M, Artist = artists.Single(a => a.Name == "Zeca Pagodinho"), AlbumArtUrl = "/Content/Images/placeholder.gif" }, }.ForEach(a => context.Albums.Add(a)); } } }
2.6 Order
using using using using System.Collections.Generic; System.ComponentModel; System.ComponentModel.DataAnnotations; System.Web.Mvc;
[ScaffoldColumn(false)] public int OrderId { get; set; } [ScaffoldColumn(false)] public System.DateTime OrderDate { get; set; } [ScaffoldColumn(false)] public string Username { get; set; } [Required(ErrorMessage = "First Name is required")] [DisplayName("First Name")] [StringLength(160)] public string FirstName { get; set; } [Required(ErrorMessage = "Last Name is required")] [DisplayName("Last Name")] [StringLength(160)] public string LastName { get; set; } [Required(ErrorMessage = "Address is required")] [StringLength(70)] public string Address { get; set; } [Required(ErrorMessage = "City is required")] [StringLength(40)] public string City { get; set; } [Required(ErrorMessage = "State is required")] [StringLength(40)] public string State { get; set; } [Required(ErrorMessage = "Postal Code is required")] [DisplayName("Postal Code")] [StringLength(10)] public string PostalCode { get; set; } [Required(ErrorMessage = "Country is required")] [StringLength(40)] public string Country { get; set; } [Required(ErrorMessage = "Phone is required")] [StringLength(24)]
public string Phone { get; set; } [Required(ErrorMessage = "Email Address is required")] [DisplayName("Email Address")] [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.]+\.[A-Za-z]{2,4}", ErrorMessage = "Email is is not valid.")] [DataType(DataType.EmailAddress)] public string Email { get; set; } [ScaffoldColumn(false)] public decimal Total { get; set; } public List<OrderDetail> OrderDetails { get; set; } } }
2.7 OrderDetail
namespace MvcMusicStore.Models { public class OrderDetail { public int OrderDetailId { get; set; } public int OrderId { get; set; } public int AlbumId { get; set; } public int Quantity { get; set; } public decimal UnitPrice { get; set; } public virtual Album Album { get; set; } public virtual Order Order { get; set; } } }
2.8 Cart
using System.ComponentModel.DataAnnotations; namespace MvcMusicStore.Models { public class Cart
{ [Key] public public public public public int RecordId { get; set; } string CartId { get; set; } int AlbumId { get; set; } int Count { get; set; } System.DateTime DateCreated { get; set; }
2.9 ShoppingCart
using using using using using System; System.Collections.Generic; System.Linq; System.Web; System.Web.Mvc;
namespace MvcMusicStore.Models { public partial class ShoppingCart { MusicStoreEntities storeDB = new MusicStoreEntities(); string ShoppingCartId { get; set; } public const string CartSessionKey = "CartId"; public static ShoppingCart GetCart(HttpContextBase context) { var cart = new ShoppingCart(); cart.ShoppingCartId = cart.GetCartId(context); return cart; } // Helper method to simplify shopping cart calls public static ShoppingCart GetCart(Controller controller)
{ return GetCart(controller.HttpContext); } public void AddToCart(Album album) { // Get the matching cart and album instances var cartItem = storeDB.Carts.SingleOrDefault( c => c.CartId == ShoppingCartId && c.AlbumId == album.AlbumId); if (cartItem == null) { // Create a new cart item if no cart item exists cartItem = new Cart { AlbumId = album.AlbumId, CartId = ShoppingCartId, Count = 1, DateCreated = DateTime.Now }; storeDB.Carts.Add(cartItem); } else { // If the item does exist in the cart, then add one to the quantity cartItem.Count++; } // Save changes storeDB.SaveChanges(); } public int RemoveFromCart(int id) { // Get the cart var cartItem = storeDB.Carts.Single( cart => cart.CartId == ShoppingCartId && cart.RecordId == id);
int itemCount = 0; if (cartItem != null) { if (cartItem.Count > 1) { cartItem.Count--; itemCount = cartItem.Count; } else { storeDB.Carts.Remove(cartItem); } // Save changes storeDB.SaveChanges(); } return itemCount; } public void EmptyCart() { var cartItems = storeDB.Carts.Where(cart => cart.CartId == ShoppingCartId); foreach (var cartItem in cartItems) { storeDB.Carts.Remove(cartItem); } // Save changes storeDB.SaveChanges(); } public List<Cart> GetCartItems() { return storeDB.Carts.Where(cart => cart.CartId == ShoppingCartId).ToList(); }
public int GetCount() { // Get the count of each item in the cart and sum them up int? count = (from cartItems in storeDB.Carts where cartItems.CartId == ShoppingCartId select (int?)cartItems.Count).Sum(); // Return 0 if all entries are null return count ?? 0; } public decimal GetTotal() { // Multiply album price by count of that album to get // the current price for each of those albums in the cart // sum all album price totals to get the cart total decimal? total = (from cartItems in storeDB.Carts where cartItems.CartId == ShoppingCartId select (int?)cartItems.Count * cartItems.Album.Price).Sum(); return total ?? decimal.Zero; } public int CreateOrder(Order order) { decimal orderTotal = 0; var cartItems = GetCartItems(); // Iterate over the items in the cart, adding the order details for each foreach (var item in cartItems) { var orderDetail = new OrderDetail { AlbumId = item.AlbumId, OrderId = order.OrderId,
UnitPrice = item.Album.Price, Quantity = item.Count }; // Set the order total of the shopping cart orderTotal += (item.Count * item.Album.Price); storeDB.OrderDetails.Add(orderDetail); } // Set the order's total to the orderTotal count order.Total = orderTotal; // Save the order storeDB.SaveChanges(); // Empty the shopping cart EmptyCart(); // Return the OrderId as the confirmation number return order.OrderId; } // We're using HttpContextBase to allow access to cookies. public string GetCartId(HttpContextBase context) { if (context.Session[CartSessionKey] == null) { if (!string.IsNullOrWhiteSpace(context.User.Identity.Name)) { context.Session[CartSessionKey] = context.User.Identity.Name; } else { // Generate a new random GUID using System.Guid class Guid tempCartId = Guid.NewGuid();
// Send tempCartId back to client as a cookie context.Session[CartSessionKey] = tempCartId.ToString(); } } return context.Session[CartSessionKey].ToString(); } // When a user has logged in, migrate their shopping cart to // be associated with their username public void MigrateCart(string userName) { var shoppingCart = storeDB.Carts.Where(c => c.CartId == ShoppingCartId); foreach (Cart item in shoppingCart) { item.CartId = userName; } storeDB.SaveChanges(); } } }
2.10 AccountModels
using using using using using using System; System.Collections.Generic; System.ComponentModel.DataAnnotations; System.Globalization; System.Web.Mvc; System.Web.Security;
[Display(Name = "Current password")] public string OldPassword { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public class LogOnModel { [Required] [Display(Name = "User name")] public string UserName { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [Display(Name = "Remember me?")] public bool RememberMe { get; set; } } public class RegisterModel { [Required] [Display(Name = "User name")] public string UserName { get; set; } [Required] [DataType(DataType.EmailAddress)] [Display(Name = "Email address")] public string Email { get; set; }
[Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } }