Accessing different models from controllers - asp.net

I'm pretty new to MVC, it's my first project and I'm trying to learn best practices. I'm using Entity Framework.
Here is the thing:
I have two models, one is for overtime work records and other one for accounting records.
When I create an overtime work record, I want to create an accounting record too. So lets say I created overtime record with 2 hours of work, I want to create an accounting record with value of "hours of work (2) * employees overtime work salary".
I can easily do this in OvertimeController's create method but I'm not sure if I should access other models (Accounting Model) from that controller.
What's the best way to do it?
Here is my models, i'm using code first:
Accounting
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int AccountingId { get; set; }
public decimal AccountingType { get; set; }
public decimal AccountingMethod { get; set; }
public string AccountingNote { get; set; }
public decimal AccountingBorc { get; set; }
public decimal AccountingAlacak { get; set; }
public decimal WorkerId { get; set; }
public decimal PhaseId { get; set; }
public virtual Worker Worker { get; set; }
public virtual Phase Phase { get; set; }
Overhours
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int OverhourId { get; set; }
public int WorkerId { get; set; }
public int PhaseId { get; set; }
public int OverhourAmount { get; set; }
public DateTime OverhourDate { get; set; }
public virtual Worker Worker { get; set; }
public virtual Phase Phase { get; set; }
Thanks

Related

Entity Framework Core Navigation Properties and Joins, Correct Pattern

I'm struggling to understand the best way to implement some database relationships in EF Core.
Specifically, it involves the navigation properties, where you make a collection in the parent and an object in the child.
Looking at the MS docs here
Relationships, navigation properties, and foreign keys
there is the typical use case presented of a parent child relationship
public class Course
{
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
public int DepartmentID { get; set; }
public virtual Department Department { get; set; }
}
public class Department
{
public Department()
{
this.Courses = new HashSet<Course>();
}
public int DepartmentID { get; set; }
public string Name { get; set; }
public decimal Budget { get; set; }
public DateTime StartDate { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
Now this is fine for the above use case.
However, I am working on a specification system for process recipes. There are lots of machines, materials, areas, buildings and other things involved.
One of the tables in the database is "Unit", as in unit of measurement - that is kg, m, cm, etc.
This table is used as a lookup in many tables in the database, at least 20.
As such, if I've understood the recommended approach, I would end up with
pubic class Unit
{
public Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Recipes> Recipes{ get; set; }
public virtual ICollection<Coll2> Coll2{ get; set; }
public virtual ICollection<Coll3> Coll2{ get; set; }
public virtual ICollection<Coll4> Coll2{ get; set; }
public virtual ICollection<Coll5> Coll2{ get; set; }
public virtual ICollection<Coll..n> Coll..n{ get; set; }
}
This applies not just for unit, but also for quite a few other generic lookup items, such as a warehouse. There are many entities that use a link to the warehouse.
What is the correct approach when using this kind of lookup?
I'm sorry if things aren't clear, hopefully they are.

Online Shop - Create an order with multiple products MVC .net

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 !!

Foreign Keys wont create in SQLite database using SQLite.net

I am trying to set up a SQLite database using SQLite.Net and SQLiteNetExtensions. I cant seem to get the foreign keys to create in the database. I have dropped all tables and used the model classes to recreate them again. I have checked the pragma in SQLite manager and foreign keys are turned on. In my example, a plot can have many trees. Any suggestions on what i might be missing?
public class Tree
{
[PrimaryKey, AutoIncrement]
public int TreeId { get; set; }
[NotNull]
public int TreeNumber { get; set; }
[NotNull]
public double Dbhob { get; set; }
public double? Height { get; set; }
[NotNull,Default(value: false)]
public bool? HeightTree { get; set; }
public string QualityCode { get; set; }
[ForeignKey(typeof(Plot))]
public int PlotId { get; set; }
[ManyToOne]
public Plot PlotInverse { get; set; }
}
public class Plot
{
[PrimaryKey, AutoIncrement]
public int PlotId { get; set; }
[NotNull, Unique]
public System.Guid PlotGuid { get; set; }
[NotNull, MaxLength(60)]
public string Strata { get; set; }
[NotNull, MaxLength(60)]
public string PlotNumber { get; set; }
public DateTime MeasureDate { get; set; }
[MaxLength(70)]
public String AssessorLead { get; set; }
[MaxLength(60)]
public String AssessorCrew { get; set; }
[Default(value: 0)]
public double PlotArea { get; set; }
public double BasalArea { get; set; }
[OneToMany("PlotId","PlotId")]
public List<Tree> Trees { get; set; }
}
Foreign keys attributes are not created in the sqlite database as sqlite-net doesn't have support for Foreign Keys and SQLite-Net Extensions is built on top of it. They are used in runtime to save and load related objects.
As a side note, you should change this line:
[OneToMany("PlotId","PlotId")]
public List<Tree> Trees { get; set; }
To this:
[OneToMany("PlotId","PlotInverse")]
public List<Tree> Trees { get; set; }
or remove it all together and let auto-discovery do its magic:
[OneToMany]
public List<Tree> Trees { get; set; }

MVC EF Code First one to one relationship error

I want to have a list of stands (at a trade show) and a list of exhibitors.
The list of stands is separate to the list of exhibitors - however, once registered, I want the exhibitor to be able to book a stand.
When they select/book a stand - I would like to then be able to have a list the stands in my view, and also show the associated exhibitor who has booked it.
Likewise, I would like to list in another view, the exhibitors, and also which stand they have booked.
So I'm trying to setup a one to one relationship (using EF CodeFirst).
However, when trying to add a controller for either the Stand or the Exhibitor, I get the following error:
My models are:
public class Stand
{
public int StandID { get; set; }
public string Description { get; set; }
public bool Booked { get; set; }
public int ExhibitorID { get; set; }
public virtual Exhibitor Exhibitor { get; set; }
}
public class Exhibitor
{
public int ExhibitorID { get; set; }
public string Company { get; set; }
public int StandID { get; set; }
public virtual Stand Stand { get; set; }
}
I'm certain it's something to do with the "Virtual" part of the models.
Can anyone please help point out what should be updated, to allow the connection?
Thank you,
Mark
EF doesn't know which entity is the principal (parent) and which is the dependent (child). You need to declare a foreign key on the item that entity that should come first. You can do this with an annotation or a fluent mapping.
Annotation
Add the following namespace:
using System.ComponentModel.DataAnnotations.Schema;
Annotate your Stand class with the following annotation:
public class Stand
{
[ForeignKey("Exhibitor")]
public int StandID { get; set; }
public string Description { get; set; }
public bool Booked { get; set; }
public int ExhibitorID { get; set; }
public virtual Exhibitor Exhibitor { get; set; }
}
Fluent Mapping
Override your OnModelCreating method in your DbContext class to include:
modelBuilder.Entity<Stand>()
.HasOptional(s => s.Exhibitor)
.WithRequired(e => e.Stand);
The model you have created is not possible to work with relational databases. The Stand needs an ExibitorId while Exibitor need a StandId. The cyclic relationship does not allow you to insert any rows to either tables.
Assuming an Exibitor may have more than one Stand and converting the relationship to one-to-many is one option.
public class Stand
{
public int StandID { get; set; }
public string Description { get; set; }
public bool Booked { get; set; }
public int? ExhibitorID { get; set; }
public virtual Exhibitor Exhibitor { get; set; }
}
public class Exhibitor
{
public int ExhibitorID { get; set; }
public string Company { get; set; }
public virtual ICollection<Stand> Stands { get; set; }
}
Or you can use shared primary key mapping to make the relationship one-to-one. Where Stand is the principal entity. The Exibitor will use the StandID as its PK.
public class Stand
{
public int StandID { get; set; }
public string Description { get; set; }
public bool Booked { get; set; }
public virtual Exhibitor Exhibitor { get; set; }
}
public class Exhibitor
{
public int ExhibitorID { get; set; }
public string Company { get; set; }
public virtual Stand Stand { get; set; }
}
Using the Fluent API to configure the relationship.
modelBuilder.Entity<Exibitor>().HasRequired(e => e.Stand)
.WithOptional(s => s.Exibitor);

How do I build a class that shares a table with multiple columns in MVC3?

I have a Job table
public class Job
{
public int JobId { get; set; }
public int SalesManagerId { get; set; }
public int SalesRepId { get; set; }
}
and a Person table
public class Person
{
public int PersonId { get; set; }
public int FirstName { get; set; }
public int LastName { get; set; }
}
My question is, how do I link the SalesManagerId to the Person (or PersonId) as well as the SalesRepId to the Person (PersonId)? The Sales Manager and Sales Rep are independent of each other. I just don't want to make 2 different lists to support the Sales Manager and Sales Rep roles.
I'm new to MVC3, but it seems public virtual Person Person {get; set; } would be the way to go, but that doesn't work.
Any help would be appreciated!
Thanks!
Change your Job class like this
public class Job
{
public int JobId { get; set; }
public virtual Person SalesManager { set; get; }
public virtual Person SalesRep { set; get; }
}
This will create the Job table with 3 columns. JobId, SalesManager_PersonID (ForiegnKey) ,SalesRep_PersonID (Foriegn key)

Resources