public class Product { public int ProductId { get; set; } public string Name { get; set; } public int CategoryId { get; set; } public virtual Category Category { get; set; } public int Price { get; set; } public DateTime CreationDate { get; set; } public string Description { get; set; } } public class Category { public int CategoryId { get; set; } public string Name { get; set; } public virtual ICollection<Product> Products { get; set; } } public class ProductsContext : DbContext { public DbSet<Category> Categories { get; set; } }
Scaffold Controller [ ] –Repository
Scaffold Controller Product –Repository
public interface IProductRepository { IQueryable<Product> All { get; } IQueryable<Product> AllIncluding(params Expression<Func<Product, object>>[] includeProperties); Product Find(int id); void InsertOrUpdate(Product product); void Delete(int id); void Save(); }
public class ProductRepository : IProductRepository { ProductsContext context = new ProductsContext(); public IQueryable<Product> All { get { return context.Products; } } public IQueryable<Product> AllIncluding(params Expression<Func<Product, object>>[] includeProperties) { IQueryable<Product> query = context.Products; foreach (var includeProperty in includeProperties) { query = query.Include(includeProperty); } return query; } public Product Find(int id) { return context.Products.Find(id); } public void InsertOrUpdate(Product product) { if (product.ProductId == default(int)) { // New entity context.Products.Add(product); } else { // Existing entity context.Entry(product).State = EntityState.Modified; } } public void Delete(int id) { var product = context.Products.Find(id); context.Products.Remove(product); } public void Save() { context.SaveChanges(); } }
class RepoModule : NinjectModule { public override void Load() { Bind<ICategoryRepository>().To<CategoryRepository>(); Bind<IProductRepository>().To<ProductRepository>(); } }
var modules = new INinjectModule[] { new RepoModule() }; var kernel = new StandardKernel(modules); RegisterServices(kernel); return kernel;
public class ProductsController : Controller { private readonly IProductRepository productRepository; public ProductsController(IProductRepository productRepository) { this.productRepository = productRepository; } }
public class ProductController : Controller { private static Logger log = LogManager.GetCurrentClassLogger(); public ActionResult DoStuff() { //very important stuff log.Info("Everything is OK!"); return View(); } }
public class ProductIndexDefinition : IIndexDefinition<Product> { public Document Convert(Product entity) { var document = new Document(); document.Add(new Field("ProductId", entity.ProductId.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED)); document.Add(new Field("Name", entity.Name, Field.Store.YES, Field.Index.ANALYZED)); if (!string.IsNullOrEmpty(entity.Description)) { document.Add(new Field("Description", entity.Description, Field.Store.YES, Field.Index.ANALYZED)); } document.Add(new Field("CreationDate", DateTools.DateToString(entity.CreationDate, DateTools.Resolution.DAY), Field.Store.YES, Field.Index.NOT_ANALYZED)); if (entity.Price != null) { var priceField = new NumericField("Price", Field.Store.YES, true); priceField.SetIntValue(entity.Price); document.Add(priceField); } document.Add(new Field("CategoryId", entity.CategoryId.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED)); return document; } public Term GetIndex(Product entity) { return new Term("ProductId", entity.ProductId.ToString()); } }
public ActionResult Create(Product product) { if (ModelState.IsValid) { product.CreationDate = DateTime.Now; productRepository.InsertOrUpdate(product); productRepository.Save(); // index location var indexLocation = new FileSystemIndexLocation(new DirectoryInfo(Server.MapPath("~/Index"))); var definition = new ProductIndexDefinition(); var task = new EntityUpdateTask<Product>(product, definition, indexLocation); task.IndexOptions.RecreateIndex = false; task.IndexOptions.OptimizeIndex = true; //IndexQueue.Instance.Queue(task); var indexWriter = new DirectoryIndexWriter(new DirectoryInfo(Server.MapPath("~/Index")), false); using (var indexService = new IndexService(indexWriter)) { task.Execute(indexService); } return RedirectToAction("Index"); } else { ViewBag.PossibleCategories = categoryRepository.All; return View(); } }
public class ProductResultDefinition : IResultDefinition<Product> { public Product Convert(Document document) { var product = new Product(); product.ProductId = document.GetValue<int>("ProductId"); product.Name = document.GetValue("Name"); product.Price = document.GetValue<int>("Price"); product.CategoryId = document.GetValue<int>("CategoryId"); product.CreationDate = DateTools.StringToDate(document.GetValue("CreationDate")); product.Description = document.GetValue("Description"); return product; } }
public class ProductQuery : QueryBase { public ProductQuery(Query query) : base(query) { } public ProductQuery() { } public ProductQuery WithKeywords(string keywords) { if (!string.IsNullOrEmpty(keywords)) { string[] fields = { "Name", "Description" }; var parser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_29, fields, new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29)); Query multiQuery = parser.Parse(keywords); this.AddQuery(multiQuery); } return this; } } }
public ActionResult Search(string searchText, bool? orderByDate) { string IndexPath = Server.MapPath("~/Index"); var indexSearcher = new DirectoryIndexSearcher(new DirectoryInfo(IndexPath), true); using (var searchService = new SearchService(indexSearcher)) { var query = new ProductQuery().WithKeywords(searchText); var result = searchService.SearchIndex<Product>(query.Query, new ProductResultDefinition()); if (orderByDate.HasValue) { return View(result.Results.OrderBy(x => x.CreationDate).ToList()) } return View(result.Results.ToList()); } }
CREATE PROCEDURE dbo.aspnet_Membership_FindUsersByName @ApplicationName nvarchar(256), @UserNameToMatch nvarchar(256), @PageIndex int, @PageSize int AS BEGIN DECLARE @ApplicationId uniqueidentifier SELECT @ApplicationId = NULL SELECT @ApplicationId = ApplicationId FROM dbo.aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName IF (@ApplicationId IS NULL) RETURN 0 -- Set the page bounds DECLARE @PageLowerBound int DECLARE @PageUpperBound int DECLARE @TotalRecords int SET @PageLowerBound = @PageSize * @PageIndex SET @PageUpperBound = @PageSize - 1 + @PageLowerBound -- Create a temp table TO store the select results CREATE TABLE #PageIndexForUsers ( IndexId int IDENTITY (0, 1) NOT NULL, UserId uniqueidentifier ) -- Insert into our temp table INSERT INTO #PageIndexForUsers (UserId) SELECT u.UserId FROM dbo.aspnet_Users u, dbo.aspnet_Membership m WHERE u.ApplicationId = @ApplicationId AND m.UserId = u.UserId AND u.LoweredUserName LIKE LOWER(@UserNameToMatch) ORDER BY u.UserName SELECT u.UserName, m.Email, m.PasswordQuestion, m.Comment, m.IsApproved, m.CreateDate, m.LastLoginDate, u.LastActivityDate, m.LastPasswordChangedDate, u.UserId, m.IsLockedOut, m.LastLockoutDate FROM dbo.aspnet_Membership m, dbo.aspnet_Users u, #PageIndexForUsers p WHERE u.UserId = p.UserId AND u.UserId = m.UserId AND p.IndexId >= @PageLowerBound AND p.IndexId <= @PageUpperBound ORDER BY u.UserName SELECT @TotalRecords = COUNT(*) FROM #PageIndexForUsers RETURN @TotalRecords END
CREATE PROCEDURE dbo.aspnet_Profile_GetProfiles @ApplicationName nvarchar(256), @ProfileAuthOptions int, @PageIndex int, @PageSize int, @UserNameToMatch nvarchar(256) = NULL, @InactiveSinceDate datetime = NULL AS BEGIN DECLARE @ApplicationId uniqueidentifier SELECT @ApplicationId = NULL SELECT @ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName IF (@ApplicationId IS NULL) RETURN -- Set the page bounds DECLARE @PageLowerBound int DECLARE @PageUpperBound int DECLARE @TotalRecords int SET @PageLowerBound = @PageSize * @PageIndex SET @PageUpperBound = @PageSize - 1 + @PageLowerBound -- Create a temp table TO store the select results CREATE TABLE #PageIndexForUsers ( IndexId int IDENTITY (0, 1) NOT NULL, UserId uniqueidentifier ) -- Insert into our temp table INSERT INTO #PageIndexForUsers (UserId) SELECT u.UserId FROM dbo.aspnet_Users u, dbo.aspnet_Profile p WHERE ApplicationId = @ApplicationId AND u.UserId = p.UserId AND (@InactiveSinceDate IS NULL OR LastActivityDate <= @InactiveSinceDate) AND ( (@ProfileAuthOptions = 2) OR (@ProfileAuthOptions = 0 AND IsAnonymous = 1) OR (@ProfileAuthOptions = 1 AND IsAnonymous = 0) ) AND (@UserNameToMatch IS NULL OR LoweredUserName LIKE LOWER(@UserNameToMatch)) ORDER BY UserName SELECT u.UserName, u.IsAnonymous, u.LastActivityDate, p.LastUpdatedDate, DATALENGTH(p.PropertyNames) + DATALENGTH(p.PropertyValuesString) + DATALENGTH(p.PropertyValuesBinary) FROM dbo.aspnet_Users u, dbo.aspnet_Profile p, #PageIndexForUsers i WHERE u.UserId = p.UserId AND p.UserId = i.UserId AND i.IndexId >= @PageLowerBound AND i.IndexId <= @PageUpperBound SELECT COUNT(*) FROM #PageIndexForUsers DROP TABLE #PageIndexForUsers END
public class AjaxProductsController : Controller { private readonly IProductRepository productRepository; public AjaxProductsController(IProductRepository productRepository) { this.productRepository = productRepository; } public ActionResult Details(int id) { return Json(productRepository.Find(id)); } public ActionResult List(int category) { var products = from p in productRepository.All where p.CategoryId == category select p; return Json(products.ToList()); } }
public class ProductsController : Controller { private readonly IProductRepository productRepository; public ProductsController(IProductRepository productRepository) { this.productRepository = productRepository; } public ActionResult List(int category) { var products = from p in productRepository.All where p.CategoryId == category select p; if (Request.IsAjaxRequest()) { return Json(products.ToList()); } return View(products.ToList()); } }
[HttpPost] public ActionResult Create(Product product) { if (ModelState.IsValid) { productRepository.InsertOrUpdate(product); productRepository.Save(); return RedirectToAction("Index"); } return View(); }
public Product InsertOrUpdate(Product product) { if (product.ProductId == default(int)) { // New entity return context.Products.Add(product); } // Existing entity context.Entry(product).State = EntityState.Modified; return context.Entry(product).Entity; }
public class ProductsController : ApiController { /* * */ public IEnumerable<Product> GetAllProducts(int category) { var products = from p in productRepository.All where p.CategoryId == category select p; return products.ToList(); } // Not the final implementation! public Product PostProduct(Product product) { var entity = productRepository.InsertOrUpdate(product); return entity; } }
public ActionResult List(string sortOrder, int category) { var products = from p in productRepository.All where p.CategoryId == category select p; switch (sortOrder.ToLower()) { case "name": products = products.OrderBy(x => x.Name); break; case "desc": products = products.OrderBy(x => x.Description); break; } return Json(products.ToList()); }
public IQueryable<Product> GetAllProducts(int category) { var products = from p in productRepository.All where p.CategoryId == category select p; return products; }
http://localhost/api/products?category=1&$orderby=Name
Source: https://habr.com/ru/post/143024/
All Articles