How can I display the number of posts? - asp.net-core

I create a forum and I have a problem: how can I add the number of posts for each category? I would like to use the viewmodel
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual List<Post> Posts { get; set; }
}
public IActionResult Index()
{
var model = categoryService.GetAll();
return View(model);
}

You can add a property to your ViewModel that will retrieve the number of Post's for that Category.
It could look something like this:
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual List<Post> Posts { get; set; }
public int PostCount
{
get
{
return Posts != null ? Posts.Count : 0;
}
}
}

Related

Asp net core to list the author's books on the page

I want to show the books belonging to the author on the author edit page, but all the books are displayed on the page. I want to select and show only the books belonging to that author.
Admin Controller Page :
[HttpGet]
public IActionResult AuthorEdit(int? id)
{
if(id==null)
{
return NotFound();
}
var entity = _authorService.GetByIdWithBooks((int)id);
if(entity==null)
{
return NotFound();
}
var model = new AuthorModel()
{
Books = _bookService.GetAll(),
AuthorId = entity.AuthorId,
NameLastName = entity.NameLastName,
Description = entity.Description,
};
return View(model);
}
GetByIdWithBooks
public Author GetByIdWithBooks(int authorId)
{
return BookContext.Authors
.Where(i=>i.AuthorId==authorId)
.FirstOrDefault();
}
Book Model :
public class Book
{
public int BookId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public double? Price { get; set; }
public string Description { get; set; }
public string ImageUrl { get; set; }
public string BarcodeNumber { get; set; }
public int PageCount { get; set; }
public string FirstPrintDate { get; set; }
public bool IsApproved { get; set; }
public bool IsHome { get; set; }
public DateTime DateAdded { get; set; }
public List<BookCategory> BookCategories { get; set; }
public int AuthorId { get; set; }
public Author Author { get; set; }
public int PublisherId { get; set; }
public Publisher Publisher { get; set; }
}
Author Model :
public class Author
{
public int AuthorId { get; set; }
public string NameLastName { get; set; }
public string ImageUrl { get; set; }
public string Description { get; set; }
public List<Book> Books { get; set; }
}
If you're using EF you could just change GetByIdWithBooks() method to do it, and it would make sense.
public Author GetByIdWithBooks(int authorId)
{
return BookContext.Authors
.Include(c => c.Books)
.Where(i=>i.AuthorId==authorId)
.FirstOrDefault();
}
Since you have a FK between Books -> Author the "Include" would make the necessary joins to bring back the related books.
Or, if you want to keep the _booksService.GetAll() call, which in my opinion, may not make a lot of sense:
_bookService.GetAll().Where(c => c.AuthorId == id)
Which should probably be a different method inside your service.
Is that what you were trying to achieve?

How to configure One to Many relationship in Entity Framework

I am creating API in ASP .NET Core that will retrieve posts with user Id. Post should contain text and Id of a user who posted it.
I have two models Users and Posts and I need help on how to configure this relationship
I want one User to have many posts
Currently my user model contains
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public List<Post> Posts { get; set; }
}
And my Post model
public class Post
{
public int Id { get; set; }
public string Text { get; set; }
}
What is the best way to do this ?
One to many relationships ( User to have many posts).
public class User{
public int Id { get; set; }
public string Username { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int Id { get; set; }
public string Text { get; set; }
//Navigation
public int UserId { get; set; }
public User User{ get; set; }
}
this is your Model Class:
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public Virtual List<Post> Posts { get; set; }
}
public class Post
{
public int Id { get; set; }
public string Text { get; set; }
public int UserId { get; set; }
public Virtual User User { get; set; }
}
and in your DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// configures one-to-many relationship
modelBuilder.Entity<User>().HasMany(x=>x.Posts).WithRequired(x=>x.User)
.HasForeignKey<int>(s => s.UserId);
}

How to show and search a list of products in asp.net core?

I would like to build these functionalities to a project using Asp.Net Core MVC.
Could someone please guide me through, How I can approach these steps:
View a list of product types for a given product category or for all categories.
I have created an ASP.NET Core MVC project with Identity authentication, where the user could register and log in.
I also have these Models created.
namespace Company.Models
{
public class ProductType
{
public ProductType()
{
Products = new List<Product>();
}
public long ProductTypeId { get; set; }
public string ProductName { get; set; }
public string ProductInfo { get; set; }
public string Location { get; set; }
public ProductTypeStatus Status { get; set; }
public string ImageUrl { get; set; }
public string Manufacturer { get; set; }
public string AdminComment { get; set; }
public Category Categories { get; set; }
public ICollection<Product> Products { get; protected set; }
}
public enum ProductTypeStatus
{
Available,
ReservedAdmin
}
public enum ProductStatus
{
Available,
ReservedLoaner,
ReservedAdmin,
Loaned,
Defect,
Trashed,
Lost,
NeverReturned
}
namespace Company.Models
{
public class Product
{
public long ProductId { get; set; }
public long ProductTypeId { get; set; }
public int ProductNumber { get; set; }
public string SerialNo { get; set; }
public ProductStatus Status { get; set; }
public string AdminComment { get; set; }
public string UserComment { get; set; }
public long? CurrentLoanInformationId { get; set; }
}
}
namespace Company.Models
{
public class Category
{
public Category()
{
ProductTypes = new List<ProductType>();
}
public int CategoryId { get; set; }
public string Name { get; set; }
public ICollection<ProductType> ProductTypes
{
get; protected set;
}
}
I have recently turned to Asp.Net Core MVC. So this is a new envirnoment for me to get startd. Though, I did follow the msdn tutorials on asp.net mvc.
I APPRECIATE any help!
I saw your model design I think you missing 1 small thing that is relationship between Product and Category.
1 Product will be in 1 Category
So to add 1 to 1 relationship you need to adjust your model like this. You can view more here
namespace Company.Models
{
public class Product
{
public long ProductId { get; set; }
public long ProductTypeId { get; set; }
public int ProductNumber { get; set; }
public string SerialNo { get; set; }
public ProductStatus Status { get; set; }
public string AdminComment { get; set; }
public string UserComment { get; set; }
public long? CurrentLoanInformationId { get; set; }
public Category Category { get;set; }
}
}
namespace Company.Models
{
public class Category
{
public Category()
{
ProductTypes = new List<ProductType>();
}
public int CategoryId { get; set; }
public string Name { get; set; }
public ICollection<ProductType> ProductTypes
{
get; protected set;
}
}
}
So when you update your model you will need to run ef migration to apply change to db. Detail can be found here
And finally you need to write the code to query some thing like
var query = _db.Product.Where(x => x.Category == "Book");
You can read how to write ef query in c# here

Web API 2 OData v4 Requesting a Derived Entity Collection keep response 404

I m trying this tutorial: Requesting a Derived Entity Collection
When i make this request:
GET : http://tdd.stooges.com.my/api/paymentAbles?$format=application/json
I get this response:
{
"#odata.context":"http://tdd.stooges.com.my/api/$metadata#paymentAbles",
"value":[
{
"#odata.type":"#EFDB.Topup","id":1
},
{
"#odata.type":"#EFDB.Order","id":7
}
]
}
It is OK. But when i try this request:
GET : http://tdd.stooges.com.my/api/paymentAbles/EFDB.Order?$format=application/json
I get the response 404
I found a similar question on stackoverflow:
WCF Data Service gives 404 when making OData requests for derived types,
but the solution make all http request return 500 internal error.
How can I solve the problem? You can use this site: http://tdd.stooges.com.my for testing (for example using firebug to view teh request/response details).
Update :
modelBuilder.Entity<PaymentAble>()
.Map<Topup>(s => s.Requires("type").HasValue("topup"))
.Map<Order>(m => m.Requires("type").HasValue("order"));
[Table("payment_able")]
public abstract class PaymentAble
{
[Key]
public int id { get; set; }
public double amount { get; set; }
public string code { get; set; }
public string statusEnum { get; set; }
[ForeignKey("member")]
public int member_id { get; set; }
public virtual Member member { get; set; }
public virtual Payment payment { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTimeOffset rowCreatedDT { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[ConcurrencyCheck]
public byte[] rowVersion { get; set; }
[ForeignKey("rowCreator")]
public int rowCreatorLoginPerson_id { get; set; }
[ForeignKey("rowLastModifiedBy")]
public int rowLastModifiedByLoginPerson_id { get; set; }
public virtual LoginPerson rowCreator { get; set; }
public virtual LoginPerson rowLastModifiedBy { get; set; }
}
public class Topup : PaymentAble
{
}
public class Order : PaymentAble
{
[Column("order_GSTPercent")]
public double GSTPercent { get; set; }
[Column("order_clientName")]
public string clientName { get; set; }
[Column("order_clientEmail")]
public string clientEmail { get; set; }
[Column("order_clientHp")]
public string clientHp { get; set; }
public virtual List<OrderItem> items { get; set; }
}
[Table("order_item")]
public class OrderItem : RowInfo
{
[Key]
public int id { get; set; }
public int qty { get; set; }
public double amount { get; set; }
[ForeignKey("order")]
public int order_id { get; set; }
public virtual Order order { get; set; }
public virtual OrderCard card { get; set; }
}
public static IEdmModel GetModel()
{
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<LoginPerson>("loginPersons");
builder.EntitySet<Admin>("admins");
builder.EntitySet<Member>("members");
builder.EntitySet<Card>("cards");
builder.EntitySet<CardPackage>("cardPackages");
builder.EntitySet<Game>("games");
builder.EntitySet<Img>("imgs");
builder.EntitySet<Currency>("currencys");
builder.EntitySet<Topup>("topups");
builder.EntitySet<Order>("orders");
builder.EntitySet<OrderItem>("OrderItems");
builder.EntitySet<Payment>("payments");
builder.EntitySet<PaymentAble>("paymentAbles");
builder.Namespace = "RPC"; //test only
var gettotalFn = builder.EntityType<PaymentAble>().Collection.Function("getTotal");
gettotalFn.Returns<int>();
return builder.GetEdmModel();
}
config.MapODataServiceRoute("odata", "api", GetModel());
[ODataRoutePrefix("paymentAbles")]
public class PaymentAblesController : BaseController
{
[ODataRoute("")]
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
public IQueryable<PaymentAble> get()
{
return db.paymentAbles;
}
public async Task<IHttpActionResult> getTotal()
{
return Ok(15);
}
}

Raven Db Join on simple List

I have this kind of structure stored in Raven DB
public class AAA
{
public int Id { get; set; }
public string Name { get; set; }
}
public class BBB
{
public int Id { get; set; }
public string Name { get; set; }
public List<int> AAAIds { get; set; }
}
and I'm trying to get a query to basically show something like:
public class AAA_BBB
{
public int AAB_Id { get; set; }
public string AAA_Name { get; set; }
public bool ContainsAtLeastOneBBB { get; set; }
}
I'm trying to do something like:
var AAA_BBB = session.Query().Include(a=>a.AAAIds.Select(a=>a))
You need something like:
session.Query<BBB>().Include<BBB,AAA>(x=>x.AAAIds)