1

I am Trying to build my First application by Entity Framework 6 Code First using MVC 5 but I have a problem, my application is online restaurant which contains Items class and it contains itemprice and itemamount and I would like to calculate its value itemprice*itemamount to be saved in total cost in Orders class, How I can do that in the initializer[enter image description here][1]???

var Items = new List<MenuItem>
     {
         new MenuItem { ItemName = "Cheese Piza", Itemdesrciption="Pizza with cheese", MenuID=int.Parse("3"), ItemPrice=Decimal.Parse("15.5"), ItemAmount=int.Parse("2")},
         new MenuItem { ItemName = "Bolinez Pasta", Itemdesrciption="pasta with red sous", MenuID=int.Parse("3"),ItemPrice=Decimal.Parse("20.45"), ItemAmount=int.Parse("3")},
         new MenuItem { ItemName = "Holy Cake", Itemdesrciption="Cake with choklet sous", MenuID=int.Parse("3"), ItemPrice=Decimal.Parse("45.5"), ItemAmount=int.Parse("1")},
     };

     Items.ForEach(I => context.Item.Add(I));
        context.SaveChanges();




        var Orderss = new List<Order>
     {
         new Order { CustomerID = int.Parse("1"), ItemID=int.Parse("3"), OrderDate= DateTime.Parse("2005-09-01"),
             TotalPrice = },

     };
  • the image isnt available, please update your answere for show the image link – henoc salinas Feb 27 '18 at 15:42
  • Unless your calculation for total cost is changing frequently I wouldn't save the cost. Just calculate it when you need it. You could then use a get accessor to perform the calculation when you needed the cost. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties#the-get-accessor – Blast_dan Feb 27 '18 at 15:44
  • 1
    .. why are you using `MenuID=int.Parse("3")` rather than `MenuID=3`? – stuartd Feb 27 '18 at 15:46
  • I thought that it will not work – SallyDeveloper Feb 27 '18 at 15:48
  • It'll work. You are are just changing "3" to 3 with the int.Parse. I would probably try and focus more on basic C# stuff then trying to understand MVC 5 and EF stuff. – Blast_dan Feb 27 '18 at 15:50
  • You should realize, you'll likely have a Product, Order, and a OrderLineItem. That way the Order total can have a calculated property to sum each line item on the order. – Greg Feb 27 '18 at 16:01

3 Answers3

0

Just use var price = Items.Sum(t => t.ItemPrice); but, i guess your have to work on this code a lot :)

Abaout int.parse read this

0

You can use the computed attribute to add a computation column. This should create a price column that is calculated in the database. The private set is made so that the program can't overwrite the computation that the database provides.

public class MenuItem 
{
    [Key]
    public Int MenuID{ get; set; }
    public string ItemName { get; set; }
    public string Itemdesrciption { get; set; }
    public Int ItemAmount{ get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]      
    public string ItemPrice
    {
        get { return /* do your sum here */ }
        private set { /* needed for EF */ }
    }
}
Blast_dan
  • 1,135
  • 9
  • 18
0

I think that data is not necessary to save it in the database because it is a calculated field, I think you could show us the model of your database, to observe your logic, it is something like master detail, where the teacher could be a "Order" table and the table detail the items of that "order Details" order and one more table for the available Items "Items".

    namespace Model
{

    public class Order
    {
        public int Id { get; set; }

        public int CustomerId { get; set; }

        [ForeignKey( "CustomerId" )]
        public virtual Customer Customer { get; set; }

        public virtual List<OrderDetail> Details { get; private set; }

        public double Total { get { return Details.Sum( t => t.SubTotal ); } }

        public Order()
        {
            this.Details = new List<OrderDetail>();
        }
    }

    public class OrderDetail
    {
        public int Id { get; set; }
        public int OrderId { get; set; }
        public virtual Order Order { get; set; }

        public int ItemId { get; set; }

        [ForeignKey( "ItemId" )]
        public virtual Item Item { get; set; }

        public int Quantity { get; set; }

        public double SubTotal { get { return this.Item.Price * this.Quantity; } }
    }

    public class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public double Price { get; set; }
        public double Cost { get; set; }
    }
}

namespace Try
{
    public class Program
    {
        public static void Main()
        {
            using (DataBaseContext context = new DataBaseContext())
            {
                context.Items.AddOrUpdate( t => t.Name, 
                    new Model.Item() { Name = "MyProduct1", Price= 14.5, Cost=11.5, Description="" } ,
                    new Model.Item() { Name = "MyProduct2", Price = 16.5, Cost = 14.5, Description = "" },
                    new Model.Item() { Name = "MyProduct3", Price = 20.5, Cost = 18.5, Description = "" },
                    new Model.Item() { Name = "MyProduct4", Price = 10.5, Cost = 8.5, Description = "" }
                    );

                context.Savechanges();


                Model.Order Order= new Model.Order() { CustomerId=3};

                Order.Details.AddRange( new Model.OrderDetail[] {
                new Model.OrderDetail {  ItemId= 1, Quantity=2},
                new Model.OrderDetail {  ItemId= 2, Quantity=1},
                new Model.OrderDetail {  ItemId= 3, Quantity=5},
                new Model.OrderDetail {  ItemId= 4, Quantity=6}
                } );

                Console.WriteLine( "Total: {0} for {1} Items", Order.Total, Order.Details.Count );
                Console.ReadLine();
            }               

        }
    }
}

please enabled Lazy for auto load Navigation Properties.

henoc salinas
  • 1,044
  • 1
  • 9
  • 20