How to check completed orders when user is logged in? - asp.net

Currently I create a shop and I use ASP Identity razor pages to login, logout and registration. I have default IdentityUser. I have also ASPNetUsers table and I want reference row UserId to my other table Orders. My main purpose to achieve is when user logg in, he can check his completed orders from database. I know how to use LINQ to get order from database, but I didn't know how to connect that with Identity. I also use Session for adding item to cart if it is important.
public class AppDbContext : IdentityDbContext<IdentityUser>
{
public AppDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<Game> Games { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<SubGenre> SubGenres { get; set; }
public DbSet<CartItem> CartItems { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<ShipAddress> ShipAddresses { get; set; }
}
public class ShipAddress
{
[BindNever]
public int ShipAddressId { get; set; }
public List<Order> Orders { get; set; }
[Required(ErrorMessage = "Wpisz swoje imię!")]
[StringLength(50)]
[Display(Name = "Imię:")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Wpisz swoje nazwisko!")]
[StringLength(50)]
[Display(Name = "Nazwisko:")]
public string LastName { get; set; }
[Required(ErrorMessage = "Wpisz nazwę ulicy!")]
[StringLength(50)]
[Display(Name = "Ulica:")]
public string Address1 { get; set; }
[Required(ErrorMessage = "Wpisz numer domu/lokalu!")]
[StringLength(50)]
[Display(Name = "Nr domu/lokalu:")]
public string Address2 { get; set; }
[Required(ErrorMessage = "Wpisz kod pocztowy!")]
[StringLength(6)]
[Display(Name = "Kod pocztowy:")]
public string ZipCode { get; set; }
[Required(ErrorMessage = "Wpisz miejscowość!")]
[StringLength(50)]
[Display(Name = "Miejscowość:")]
public string City { get; set; }
[Required(ErrorMessage = "Wpisz numer kontaktowy!")]
[StringLength(9)]
[Display(Name = "Nr telefonu:")]
public string PhoneNumber { get; set; }
[BindNever]
public decimal OrderTotal { get; set; }
[BindNever]
public DateTime OrderPlaced { get; set; }
public IdentityUser User { get; set; }
public int IdentityUserId { get; set; }
}

Current Login User
var userID = User.Identity.GetUserId();
This will give your current login user id then you can apply linq for based on this id with and condition of completed order you store in table

Use User's Identity which u logged in by using
string userID = User.Identity.GetUserId();

Related

Get values to a dropdownlist associated to the UserId

I have an application that basically controls the expenses and income of a person, and an expense is associated with a type of expenditure, these types of expenditure can be created by the user and must differ from user to user.
Exemplifying best for the types of expenditure can have various options available and I can only pick one, this was implemented through a dropdownlist.
What was intended that each user had their types of expenditure and that they were different from each other, what I have is the following:
Model Expenses:
public class Expense
{
public int TipeExpenseId { get; set; }
public int ExpenseId { get; set; }
[Display(Name = "Descrição da Despesa")]
[Required]
public string ExpenseDescription { get; set; }
[Display(Name = "Valor")]
[Required]
public decimal ExpenseValue { get; set; }
public int PayementTypeId { get; set; }
[Display(Name = "Data")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}",ApplyFormatInEditMode = true)]
[Required]
public DateTime Data { get; set; }
public ExpenseTipe ExpenseTipe { get; set; }
public PaymentType PaymentType { get; set; }
[Display(Name = "Comentário")]
public string Coment { get; set; }
[ForeignKey("ApplicationUserId")]
public virtual ApplicationUser User { get; set; }
public string ApplicationUserId { get; set; }
}
Model TipeExpense:
public int ExpenseTipeId { get; set; }
[Display(Name = "Tipo de Despesa")]
[Required]
public string ExpenseTipeName { get; set; }
public virtual ApplicationUser User { get; set; }
public string ApplicationUserId { get; set; }
I want to get all the ExpenseTipe related to the user that Create it, i think i need to do something in the linq query, to not get all the list of tipe of expenses, but just the expenses that have the same Id as the User but i dont know how to do it in the Linq query, here is my controller that fills the DropDown list.
public ActionResult Create([Bind(Include = "DespesaId,TipoDespesaId,DespesaDescricao,DespesaValor,TipoPagamentoId,Data,Comentario")] Despesa despesa)
{
if (ModelState.IsValid)
{
despesa.ApplicationUserId = User.Identity.GetUserId();
db.Despesas.Add(despesa);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.TipoDespesaId = new SelectList(db.TipoDespesas, "TipoDespesaId", "TipoDespesaNome", despesa.TipoDespesaId);
ViewBag.TipoPagamentoId = new SelectList(db.TipoPagamentos, "TipoPagamentoId", "TipoPagamentoNome", despesa.TipoPagamentoId);
return View(despesa);
}
I think i need a where condition in the viewBag but dont know how to do it :S
just add a where clause to your db.TipoDespesas.
db.TipoDespesas.where(x=> x.applicationUserid == UserId)

How to retrive list of posts when searching in tags table [ASP MVC]

I want to make a search for post via tags , for example when I write in the search box "ASP" I will search for post they have same tags and return them as a list of post ...
Here is my tags table :
Also here is my book class :
[Table("Book")]
public partial class Book
{
[Key]
public int Book_id { get; set; }
[Required]
[Display(Name ="User Name")]
[StringLength(128)]
public string User_ID { get; set; }
[Required]
[Display(Name = "Title Name")]
[StringLength(70,MinimumLength =3)]
public string Book_name { get; set; }
[Display(Name = "Edition")]
[Range(1, 20)]
public int Edition { get; set; }
[Display(Name = "Category Name")]
public int Category_id { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
[Display(Name = "Publish Date")]
public DateTime Publish_date { get; set; }
[StringLength(50)]
[Display(Name = "Author Name")]
public string Author_name { get; set; }
[StringLength(128)]
[Display(Name = "Cover Image")]
public string Book_Image { get; set; }
[StringLength(128,MinimumLength =8)]
[Url]
[Display(Name = "Download Link")]
public string Download_Link { get; set; }
[StringLength(250)]
[Display(Name = "Upload Pdf")]
public string pdf_file { get; set; }
[AllowHtml]
[Column(TypeName = "text")]
[Display(Name = "Description")]
public string Book_Description { get; set; }
public int View_Count { set; get; }
[StringLength(250,MinimumLength =2,ErrorMessage ="Min Tags Input lenght is 2 char")]
[Display(Name = "Tags")]
public virtual string TagsListing { get; set; }
public virtual IList<Tag> Tags
{ get; set; }
public virtual AspNetUser AspNetUser { get; set; }
public virtual Category Category { get; set; }
}
Also tag class :
public class Tag
{
public virtual int Id
{ get; set; }
public virtual string Name
{ get; set; }
public virtual string UrlSlug
{ get; set; }
public virtual string Description
{ get; set; }
public virtual IList<Book> Books
{ get; set; }
}
I just simply want to see if the search term that the visitor searched for can be founded in tags table , and return list of books related to the same tag..
thanks
Using LINQ
var searchTerm = "Swift";
var postList = db.Books.Where(s => s.Tags.Any(g => g.Name.Contains(searchTerm))).ToList();
Contains will do a SQL equivalent of LIKE '%Swift%' . You can also try StartsWith or EndsWith as needed.

Entity Framework 1:1 relationship Code First

I'm struggling here. I've tried through data annotations and via the Fluent API and still not working correctly. Desperate for help now. Basically, I have two tables. A Company table and an Address Table. A company must have a head office address (which should live in the Address Table) and an Address must have a Company which is belongs too. I'm really struggling to set this up correctly.
I'll put the Code First Entities then show what I have already got.
[Table("Address")]
public class Address
{
[Key]
public long AddressId { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
public string Address4 { get; set; }
public string Address5 { get; set; }
public string Town { get; set; }
public string County { get; set; }
public string Country { get; set; }
public string PostCode { get; set; }
public virtual Company Company { get; set; }
public DateTime? RemovedDate { get; set; }
public long? RemovedBy { get; set; }
}
[Table("Company")]
public class Company
{
[Key ]
public long CompanyId { get; set; }
public string Name { get; set; }
public string WebsiteUrl { get; set; }
public virtual Address Address { get; set; }
public User LeadUser { get; set; }
public DateTime ActiveSince { get; set; }
public DateTime? ActiveTill { get; set; }
public string VatRegistration { get; set; }
public string LicenseKey { get; set; }
public LicenseStatus LicenseStatus { get; set; }
public bool CanAgreementBeExtended { get; set; }
public string BillingEmail { get; set; }
public string PhoneNumber { get; set; }
public string MobileNumber { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public virtual ICollection<User> Users { get; set; }
public virtual ICollection<LicenseHistory> LicenseHistories { get; set; }
}
//Seeded data inserted as follows
var testCompany = new Company
{
ActiveSince = DateTime.UtcNow,
Name = "Test Company",
LeadUser = adminUser,
DateCreated = DateTime.UtcNow,
DateUpdated = DateTime.UtcNow,
BillingEmail = "admin#test.co.uk",
CanAgreementBeExtended = true,
LicenseStatus = LicenseStatus.PendingAgreement,
MobileNumber = "1234567890",
PhoneNumber = "1234567890",
VatRegistration = "1234567890"
};
context.Companies.AddOrUpdate(u => u.Name, testCompany);
var testAddress = new Address
{
Address1 = "Test Ltd",
Address2 = "1 Test Gardens",
Address3 = "Test Heath",
Address4 = string.Empty,
Address5 = string.Empty,
County = "Test",
Town = "Test",
Country = "United Kingdom",
PostCode = "TE5 T11",
Company = testCompany
};
context.Addresses.AddOrUpdate(u => new { u.AddressId }, testAddress);
testCompany.Address = testAddress;
context.Companies.AddOrUpdate(u => u.Name, testCompany);
//Fluent API set up as follows in the OnModelCreating
modelBuilder.Entity<Address>()
.HasRequired(ad => ad.Company)
.WithOptional(s => s.Address);
Can anyone spot what I'm doing wrong? I've been playing round with different combinations for the past few days and it just doesn't work. I just keep getting errors, the latest error based on the code above is...
A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'AddressId'.
Any ideas please?
You can't have a true one to one in SQL Server (see How do I create a real one-to-one relationship in SQL Server), but there is a workaround in EF where you make the primary key of the second entity also a foreign key:
// [Table("Company")] -- not needed unless different
public class Company
{
// [Key ] -- will be key by convention
public long CompanyId { get; set; }
...
public virtual Address Address { get; set; }
}
public class Address
{
[Key, ForeignKey("Company")]
public long AddressId { get; set; }
public string Address1 { get; set; }
...
public virtual Company Company { get; set; }
}
You can also do it with fluent code like:
modelBuilder.Entity<Company>()
.HasRequired(t => t.Address)
.WithRequiredPrincipal(t => t.Company);

Database model for users with multiple capabilities

In another question, I explain my goal to create 2 different types of users with different capabilities in my ASP.Net MVC 5 website. I wonder how I would be able to modify my current database models to hold the related information based on their type. My current models are as follows:
public class User : IUser
{
public User()
: this(String.Empty)
{
}
public User(string userName)
{
UserName = userName;
Id = Guid.NewGuid().ToString();
}
[Key]
public string Id { get; set; }
[Required]
public string UserName { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public string Phone { get; set; }
public string MobilePhone { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public virtual IList<UserAddress> Addresses { get; set; }
}
public class Restaurant
{
[Key]
public int ID { get; set; }
[Required]
public string Name { get; set; }
public virtual IList<RestaurantAddress> Addresses { get; set; }
public virtual IList<RestaurantFood> Menu { get; set; }
public virtual IList<Review> Reviews { get; set; }
[DataType(DataType.Url)]
public string Website { get; set; }
[DataType(DataType.PhoneNumber)]
public string Phone { get; set; }
[DataType(DataType.PhoneNumber)]
public string Fax { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public int Seats { get; set; }
public double AverageRating { get; set; }
public double AveragePrice { get; set; }
}
One solution that comes to my mind is to move the additional info of the User class to another class and hold the foreign key for the related model in the basic user info class. Something like:
public class User : IUser
{
public User()
: this(String.Empty)
{
}
public User(string userName)
{
UserName = userName;
Id = Guid.NewGuid().ToString();
}
[Key]
public string Id { get; set; }
[Required]
public string UserName { get; set; }
public virtual ExtendedUser NormalUserInfo { get; set; }
public virtual Restaurant RestaurantInfo { get; set; }
}
public class ExtendedUser
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public string Phone { get; set; }
public string MobilePhone { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public virtual IList<UserAddress> Addresses { get; set; }
}
public class Restaurant
{
[Key]
public int ID { get; set; }
[Required]
public string Name { get; set; }
public virtual IList<RestaurantAddress> Addresses { get; set; }
public virtual IList<RestaurantFood> Menu { get; set; }
public virtual IList<Review> Reviews { get; set; }
[DataType(DataType.Url)]
public string Website { get; set; }
[DataType(DataType.PhoneNumber)]
public string Phone { get; set; }
[DataType(DataType.PhoneNumber)]
public string Fax { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public int Seats { get; set; }
public double AverageRating { get; set; }
public double AveragePrice { get; set; }
}
and in controller:
User user = BuildUser();
ExtendedUser normal = BuildNormalUser();
Restaurant rest = BuildRestaurant();
if (model.Type == UserType.NormalUser)
user.NormalUserInfo = normal;
else
user.RestaurantInfo = normal;
However, I'm not sure that this is the right thing to do.

DropDown box in ASP .Net MVC 3 Razor Entity Framework

i am new to ASP .NET and Particularly in ASP .Net MVC3 Razor...
i have created view for Clients and Executives in MVC3 Razor.
What i did is 1st i created Model called Clients.cs
namespace MVCInetClient.Model
{
[Table("tbl_Customer")]
public class Clients
{
[Required,Key,DatabaseGenerated(DatabaseGeneratedOption.None)]
[Display(Name = "Client ID")]
public int ClientId { get; set; }
[Required]
[Display(Name = "Client Name")]
public string ClientName { get; set; }
[Required]
[Display(Name = "Executive Name")]
public string ExecutiveName { get; set; }
[Required]
[Display(Name = "Contact Name")]
public string ContactPerson { get; set; }
[Display(Name = "Address")]
public string Add1 { get; set; }
[Display(Name = " ")]
public string Add2 { get; set; }
[Display(Name = " ")]
public string Add3 { get; set; }
[Display(Name = "Pincode")]
public string Pin { get; set; }
[Display(Name = "State")]
public string State { get; set; }
[Display(Name = "Country")]
public string Country { get; set; }
[Display(Name = "Phone")]
public string Phone { get; set; }
[Required]
[StringLength(10)]
[RegularExpression("\\d+")]
[Display(Name = "Mobile")]
public string Mobile { get; set; }
[Display(Name = "Fax")]
public string Fax { get; set; }
[Display(Name = "Email")]
public string Email { get; set; }
[Display(Name = "Website")]
public string Web { get; set; }
}
public class ClientsDbContext : DbContext
{
public DbSet<Clients> Clients { get; set; }
public DbSet<Executives> Executives{ get; set; }
}
}
After that i Created the Controller called ClientsController with Scaffolding Options,
Template : Controller With Read/Write actions and Views, using Entity Framework
Model Class : Clients (MVCInetClient.Models)
Data Context Class : ClientsDbContext (MVCInetClient.Models)
It Created View Create, Edit, Index, Delete Automatically and its working Fine too.
Similarly i did for model called Executives.cs
namespace MVCInetClient.Models
{
[Table("tbl_Executive")]
public class Executives
{
[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
[Display(Name = "Executive ID")]
public int ExecutiveId { get; set; }
[Required]
[Display(Name = "Executive Name")]
public string ExecutiveName { get; set; }
[Display(Name = "Address")]
public string Add1 { get; set; }
[Display(Name = " ")]
public string Add2 { get; set; }
[Display(Name = " ")]
public string Add3 { get; set; }
[Display(Name = "Pincode")]
public string Pin { get; set; }
[Display(Name = "State")]
public string State { get; set; }
[Display(Name = "Country")]
public string Country { get; set; }
[Display(Name = "Phone")]
public string Phone { get; set; }
[Required]
[StringLength(10)]
[RegularExpression("\\d+")]
[Display(Name = "Mobile")]
public string Mobile { get; set; }
[Display(Name = "Email")]
public string Email { get; set; }
}
public class ExecutivesDbContext : DbContext
{
public DbSet<Executives> Executives { get; set; }
}
}
and this too Working Fine in all views(create, edit, delete)
What i need is, i need a Dropdown list of Executive name in Clients View instead of editor Field.
i looked some tutorials but i am confused...
Please help me to solve it...
Seems like you are using EF Code First with MVC.
The simplest answer is that you need to a List of Executives, pass the list in a model back to your View, create a select list, and render a drop down list.
public ActionResult Execx()
{
Model Model = new Model();
Model.execList = dbcontext.Executives;
return View(Model);
}
In your View:
#Html.DropDownListFor(model => model.execId, new SelectList(Model.execList, "ExecutiveId", "ExecutiveName "))
This is untested code. I slapped the pieces together to give you the idea.

Resources