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)
Related
I want to create one to one relation between tables. My table is
public class StudentModel
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth { get; set; }
[Required, Display(Name="Department Name")]
public int DeptId { get; set; }
//navigration proprty
[ForeignKey("DeptId")]
public virtual DepartmentModels Department { get; set; }
public virtual StudentRegistrationModels StudentRegistration { get; set; }
}
and my other table is
public class StudentRegistrationModels
{
[Key]
public int StudentId { get; set; }
[Required]
public int CourseId { get; set; }
[Required]
public DateTime EnrollDate { get; set; }
public bool IsPaymentComplete { get; set; }
//navigration proprty
[ForeignKey("StudentId")]
public virtual StudentModel Student { get; set; }
[ForeignKey("CourseId")]
public virtual CourseModels Course { get; set; }
//oneToOneStudentRegistration
}
But when I make migration it throws an error:
Unable to determine the principal end of an association between the types 'StudentManagementSystem.Models.StudentModel' and 'StudentManagementSystem.Models.StudentRegistrationModels'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
Why is this occurring?
I believe the issue is that you have a single StudentRegistrationModel instance in your StudentModel, where the StudentRegistrationModel looks to be more of a Many-to-Many structure. Can a single student only be registered to a single course? If that were the case it would make more sense for StudentModel to just have a CourseModel reference. Since a Student probably has multiple courses, it would probably make more sense for StudentModel to have:
public virtual ICollection<StudentRegistrationModels> StudentRegistration { get; set; } = new List<StudentRegistrationModels>();
Then ensuring that your model configuration maps out the relationship. This can be done with an attribute, as part of the DbContext OnModelCreating, or using an EntityTypeConfiguration. With Attributes:
[InverseProperty("Student")] // Tells EF this collection corresponds to the Student on the StudentRegistrationModel.
public virtual ICollection<StudentRegistrationModels> StudentRegistration { get; set; } = new List<StudentRegistrationModels>();
Maybe try to add [Key] annotation to Id field in StudentModel.
using System.ComponentModel.DataAnnotations;
public class StudentModel
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth { get; set; }
[Required, Display(Name="Department Name")]
public int DeptId { get; set; }
//navigration proprty
[ForeignKey("DeptId")]
public virtual DepartmentModels Department { get; set; }
public virtual StudentRegistrationModels StudentRegistration { get; set; }
}
or if it won't work try map relationship in OnModelCreating in your data context.
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();
As the question suggests I am using ENTITY FRAMEWORK in my ASP.NET application in which I have a table which the user can add rows to and input data into it. I need to know how I can post this data back to controller.
My models : (There were generated by EF when i used database first approach)
public partial class TRA_FORMS
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public TRA_FORMS()
{
this.TRA_ITEMS = new HashSet<TRA_ITEMS>();
}
public int ID { get; set; }
[Display(Name = "Name of TRA")]
public string NAME_OF_TRA { get; set; }
[Display(Name = "Requested amount")]
public Nullable<double> AMOUNT_REQUESTED { get; set; }
[Display(Name = "Name of commitee member making application")]
public string COMMITEE_MEMBER_NAME { get; set; }
[Display(Name = "Date of last AGM")]
public Nullable<System.DateTime> DATE_OF_AGM { get; set; }
[Display(Name = "Signed")]
public string SIGNED { get; set; }
[Display(Name = "Dated")]
public Nullable<System.DateTime> DATED { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<TRA_ITEMS> TRA_ITEMS { get; set; }
}
public partial class TRA_ITEMS
{
public int ITEM_ID { get; set; }
[Display(Name = "Description of Items")]
public string DESC_OF_ITEMS { get; set; }
[Display(Name = "Quantity")]
public Nullable<int> QUANTITY { get; set; }
[Display(Name = "Cost")]
public Nullable<double> COST { get; set; }
[Display(Name = "From ID")]
public Nullable<int> FORM_ID { get; set; }
public virtual TRA_FORMS TRA_FORMS { get; set; }
}
My controller:
[HttpPost]
public ActionResult Index(TRA_FORMS traForms)
{
return View();
}
I'm not showing my view here as It's wrong and I dont know how to go about it. But the view accepts a model of type TRA_FORMS. I have a table in this view (regular html ) which has 3 columns - each for properties from the TRA_ITEMS model. The Desc of items, quantity and cost. Users can add any number of items to this table. Ideally on postback it should postback a List which holds each item added by the user but i don't know how to do this. I've looked at several Stack overflow questions related to this and been looking for solutions the whole day but I'm a newbie to ASP.NET so having trouble applying most answers i found to my scenario.
So I am building an online shop using Code-First MVC
So I created this model classes for now (don't take the types of the attributes too serious for now):
Products (Produto):
public Produto()
{
ListaProdutoEncomenda = new HashSet<Produto_Encomenda>();
}
public int ProdutoID { get; set; }
[Required]
[StringLength(50)]
public string Nome { get; set; }
[Required]
public double Preco { get; set; }
[Required]
public double Peso { get; set; }
[Required]
[StringLength(255)]
public string Descricao { get; set; }
[Required]
public double IVA { get; set; }
public string Imagem { get; set; }
public DateTime UltimaAtualizacao { get; set; }
public int Stock { get; set; }
public int CategoriaID {get;set;}
public virtual ICollection<Produto_Encomenda> ListaProdutoEncomenda { get; set; }
}
Encomenda (Order):
public class Encomenda
{
public Encomenda()
{
ListaProdutoEncomenda = new HashSet<Produto_Encomenda>();
}
[Key]
public int IDEncomenda { get; set; }
[Required]
public DateTime DataSubmissao { get; set; }
[Required]
public DateTime DataEnvio { get; set; }
[Required]
public int EstadoEnvioID { get; set; }
[StringLength(50)]
public string NomeDestino { get; set; }
[Required]
public int TipoExpedicaoID { get; set; }
[Required]
public int RegiaoDestinoID { get; set; }
[StringLength(50)]
public string MoradaDestino { get; set; }
[StringLength(50)]
public string CodPostalDestino { get; set; }
[Required]
[StringLength(50)]
public string MoradaFaturacao { get; set; }
[Required]
[StringLength(50)]
public string CodPostalFaturacao { get; set; }
public virtual ICollection<Produto_Encomenda> ListaProdutoEncomenda { get; set; }
}
And the connection table between the produtos (Products) and Encomenda (Order)
public class Produto_Encomenda
{
[Key]
public int IDProduto_Encomenda { get; set; }
[Required]
public string NomeProduto { get; set; }
[Required]
public int Quantidade { get; set; }
[Required]
public float preco { get; set; }
[Required]
public float IVA { get; set; }
public virtual Encomenda Encomenda { get; set; }
public virtual Produto Produto { get; set; }
[ForeignKey("Encomenda")]
public int IDEncomendaFK { get; set; }
[ForeignKey("Produto")]
public int IDProdutoFK { get; set; }
}
So my question is..
Let's pretend that a costumer buys 2 or 3 products or more.
How can I store all this products in a single line of an order?
Cheers and thanks a lot in advance for the time spent reading.
I'm not sure what you mean by "a single line of an order". Each product is a separate line item, and your entities already model this through the many-to-many relationship.
However, in general this setup is a very bad idea. Your order should not be directly related to products. Instead, your order should simply have an order item, and you'll create those order items based on the products that were sold. The reason for this is that products are very likely to change. If a product is removed because it's no longer available, for example, that doesn't negate the fact that it was previously sold in an order. However, in order for referential integrity to be maintained, any orders sold with that product would have to also have their relationship with that product removed. By having an entirely separate entity, i.e. order item, products can come and go, while the already created orders remain unaffected.
I guess you are looking to make a viewmodel
Create a class that contains Products and Encomenda class as property -
Model -
public class MyViewModel
{
public Produto Pinst{get;set;}
public Encomenda Einst{get;set;}
}
Controller or method-
public void SomeMethod()
{
List<MyViewModel> lst = new List<MyViewModel>();
//Now suppose
foreach(var items in listThatGetCreatedWithBuyerproductInfo)
{
MyViewModel obj = new MyViewModel ();
obj.Pinst = new Produto();
obj.Einst = new Encomenda();
//Here goes your properties from item in respected class instances
obj.Pinst.Nome = items.Nome;
obj.Einst.DataSubmissao = items.DataSubmissao;
//when you are done loading add obj to list
lst.Add(obj);
}
}
Hope it Helps if it does not tell me !!
So it's possible that what I'm trying to do isn't possible in the way I'm trying to do it, but basically in my budget model I'm wanting to have the actual amount. This is basically the total of all transactions for that budget. Maybe this needs to be calculated on the controller, but it seems cleaner if I could do it on the model. I'm using SQL server for my database and entity framework if that makes a difference.
In SQL I'm doing this search like this
Select budgetID, sum(amount) as 'Actual'
From Transactions
Group By budgetID
Also I'm having an issue with code accepting budgetID in transaction to be a foreign key. When I put that in there and try to update the database I'm told that The navigation property 'Budget' was not found on the dependent type 'BudgetApp.Models.Transaction'.
public class Budget
{
[Key]
public int ID {get; set;}
[Display(Name = "Budget" )]
[Required]
public string budgetName { get; set; }
[Display(Name = "Amount")]
[DataType(DataType.Currency)]
public double budgetAmount { get; set; }
[Display(Name = "Month")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString ="{0:MMM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime budgetMonth { get; set; }
public double budgetActual() {
double actual = 0; //somehow get total here
return actual;
}
}
public class Transaction
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Display(Name ="Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
public DateTime tranDate { get; set; }
[Display(Name = "Description")]
[Required]
public string tranDesc { get; set; }
[Display(Name = "Amount")]
public double amount { get; set; }
//[ForeignKey("Budget")]
public int budgetID { get; set; }
}
public class BudgetDBContext : DbContext
{
public DbSet<Budget> Budgets { get; set; }
public DbSet<Transaction> Transactions { get; set; }
}