Storing data in two tables at a time in Entity Framework - entity-framework

I have three tables
Products { pid, pname, price }
Orders { oid, odate }
OrderDetails { odid, oid, pid, qty, total }
I've a form which upon submission passes an array of OrderDetails which I want to store in database. But the tragedy here is I want to store current date in Order table at the same time. Now my Order table is getting populated with odate but nothing is getting inserted in my orderdetails table. And I'm using web api and the array is fetched correctly in controller. I guess this line
aOrder.AllOrders.Add(od);
in the controller has to be replaced with somethting else.
Order.cs
public class Order
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int oid { get; set; }
[DataType(DataType.DateTime)]
public DateTime odate { get; set; }
public virtual List<OrderDetail> AllOrders { get; set; }
public Order()
{
AllOrders = new List<OrderDetail>();
}
}
OrderDetail.cs
public class OrderDetail
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int odid { get; set; }
public int oid { get; set; }
public virtual Order order { get; set; }
public int pid { get; set; }
public int qty { get; set; }
public int total { get; set; }
public virtual Product Aproduct { get; set; }
public OrderDetail()
{
Aproduct = new Product();
}
}
OrderDetailsController.cs
private static readonly IOrderDetailRepository _orders = new OrderDetailRepository();
public Order Post(List<OrderDetail> orderDetails)
{
Order aOrder = new Order();
foreach(OrderDetail orderDetail in orderDetails)
{
OrderDetail od = new OrderDetail();
od.oid = orderDetail.oid;
od.pid = orderDetail.pid;
od.qty = orderDetail.qty;
od.total = orderDetail.total;
aOrder.AllOrders.Add(od);
}
aOrder.odate = DateTime.Now;
return _orders.Add(aOrder);
}
OrderDetailRepository.cs
public Order Add(Order order)
{
_db.Orders.Add(order);
_db.SaveChanges();
return order;
}

Can you try specifying a foreign key for OrderDetails:
public class OrderDetail
{
[ForeignKey("Order")]
public int oid { get; set; } //I'm guessing this is Order's PK

Related

Getting error while inserting department foreign key in Employee table

I am beginner to Entity Framework. I want to insert employees along with department as foreign key, but I am getting the following error while adding records:
The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.Employees_dbo.Departments_DepartmentId\". The conflict occurred in database \"EmpDB\", table \"dbo.Departments\", column 'Id'.\r\nThe statement has been terminated.
Department class:
namespace DbSet_Exmp.Models
{
public class Department
{
public int Id { get; set; }
public string DeptName { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
}
Employee class:
namespace DbSet_Exmp.Models
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Contact { get; set; }
public int Salary { get; set; }
public int DepartmentId { get; set; }
public virtual Department Department { get; set; }
}
}
DbContext class:
public class EmpDbContext:DbContext
{
public EmpDbContext() : base("name=myDBConString")
{
Database.SetInitializer(new DBInitializer());
}
public DbSet<Department> Departments { get; set; }
public DbSet<Employee> employees { get; set; }
}
Index action:
public ActionResult Index()
{
using (var context = new EmpDbContext())
{
Employee objEmp = new Employee() { Name = "Swara", Contact = "123569", Salary = 15000, DepartmentId = 2 };
context.employees.Add(objEmp);
context.SaveChanges();
}
return View();
}
Usually this error thrown when you are assigning a value to the ForeignKey but there is no such data with that value in ForeignKey table.
In your case there is no Department with Id = 2 in your Department table . So you can check it in your Departement table.

How to create Model based C# List from Database

I have Models created through Entity Framework as:
public partial class Order
{
public Order()
{
this.OrderDetails = new HashSet<OrderDetail>();
}
public int OrderID { get; set; }
public string OrderNo { get; set; }
public System.DateTime OrderDate { get; set; }
public string Description { get; set; }
public virtual ICollection<OrderDetail> OrderDetails { get; set; }
}
Then another Details Table:
public partial class OrderDetail
{
public int OrderItemsID { get; set; }
public int OrderID { get; set; }
public string ItemName { get; set; }
public int Quantity { get; set; }
public decimal Rate { get; set; }
public decimal TotalAmount { get; set; }
public virtual Order Order { get; set; }
}
To See the Master Detail Data I made MasterDetails model As:
public class OrderVM
{
public string OrderNo { get; set; }
public DateTime OrderDate { get; set; }
public string Description { get; set; }
public List<OrderDetail> OrderDetails {get;set;}
}
I'm trying to make a method that return a LIST with Join query results but
I'm receiving #Anonymous type error here is my Code:
public static List<OrderVM > mylist()
{
List<OrderVM> slist = new List<OrderVM>();
using (MyDatabaseEntities1 dc = new MyDatabaseEntities1())
{
var myvalues = from O in dc.Orders
join D in dc.OrderDetails
on
O.OrderID equals D.OrderID
select new
{
O.OrderID,
O.OrderDate,
D.Quantity,
D.Rate
};
foreach(var myorders in myvalues)
{
slist.Add(myorders);
}
return slist;
}
}
I need a help that how I can I create a generic list with database fields
Create new class:
public class OrderDetailsModel
{
public int OrderId { get; set; }
public DateTime OrderDate { get; set; }
public int Quantity { get; set; }
public decimal Rate { get; set; }
}
and return list of objects of this class from your method:
using (MyDatabaseEntities1 dc = new MyDatabaseEntities1())
{
var myvalues = from O in dc.Orders
join D in dc.OrderDetails
on
O.OrderID equals D.OrderID
select new OrderDetailsModel
{
OrderId = O.OrderID,
OrderDate = O.OrderDate,
Quantity = D.Quantity,
Rate = D.Rate
};
return myvalues.ToList();
}

Inserting data into multiple tables using Entity Framework

I have two tables in my database that I am filling via Web API:
Orders
________
OrderID
OrderDate
OrderStatusID
and
OrderItems
___________
OrderID
ItemID
ItemVersionID
ItemNote
ItemSortOrder
I need to insert Order and all the items for that order in two tables. OrderID is an identity field generated by the database that I will need for inserting data into OrderItems table.
Primary key for the OrderItems table is a composite key (OrderID, ItemID, ItemVersionID), it is important since the same order can contain multiple items with the same ID but different Version ID.
I was wondering if I will have to add Order and OrderItems data separately or can do so in a single controller function.
Below are my model classes:
[Table("SN_Orders")]
public class Order
{
[Key]
public int OrderID { get; set; }
public DateTime OrderDate { get; set; }
public int OrderStatusID { get; set; }
public List<OrderItem> Details { get; set; }
}
[Table("SN_OrderItems")]
public class OrderItem
{
[Column(Order = 0), Key]
public int ItemID { get; set; }
[Column(Order = 1), Key]
public int ItemVersionID { get; set; }
[Column(Order = 2), Key]
public int OrderID { get; set; }
public string ItemNote { get; set; }
public int ItemSortOrder { get; set; }
}
And below is my attempt to pass in a list of OrderItems with Order that did not work out:
[HttpPost]
public IHttpActionResult PostItemToOrder(myClass.Order ord1, List<myClass.OrderItem> itemList)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
using (MyContext ctx = new MyContext())
{
ctx.Orders.Add(ord1);
ctx.SaveChanges();
foreach (var item in itemList)
{
item.OrderID=ord1.OrderId;
ctx.OrderItems.Add(item);
ctx.SaveChanges();
}
}
}
Is that something that is possible to accomplish at once? Or will I have to insert order first, return the OrderID to the calling program and then insert Items?
Put it like this:
Your Order class should have:
public class Order
{
public int Id { get; set; }
// all rest
public virtual ICollection<OrderItem> Items { get; set; } // here is the trick
}
[HttpPost]
public IHttpActionResult PostItemToOrder(myClass.Order ord1, List<myClass.OrderItem> itemList)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
using (MyContext ctx = new MyContext())
{
var order = ord1;
order.Items = itemList;
ctx.Orders.Add(order);
ctx.SaveChanges();
}
}

Updating a relation between two Entity Framework entities?

I have two related Entity Framework 6 classes in my data layer.
public class Order
{
public int Id { get; set; }
public virtual SalesStatus SalesStatus { get; set; }
}
public class SalesStatus
{
public SalesStatus()
{
Orders = new List<Order>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual List<Order> Orders { get; set; }
}
public class OrderVM
{
public int Id { get; set; }
public SalesStatus SalesStatus { get; set; }
}
I am using Automapper to map these to my view models and back again.
cfg.CreateMap<Order, OrderVM>()
.MaxDepth(4)
.ReverseMap();
The status entity is used to populate a drop down list.
In my method I am taking the selected value and trying to update the order record to the new selected status.
private bool SaveOrderToDb(OrderVM orderVM)
{
using (var db = new MyContext())
{
var order = AutomapperConfig.MapperConfiguration.CreateMapper().Map<OrderVM, Order>(orderVM);
order.SalesStatus = db.SalesStatuses.Find(Convert.ToInt16(orderVM.SalesStatusSelectedValue));
db.Set<Order>().AddOrUpdate(order);
db.SaveChanges();
}
return true;
}
This does not update the relationship in the database. Why? What am I missing?

EF 4 CTP 5 Complex query

I have a model like the following:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Order> Orders { get; set; }
}
public class Order
{
public int Id { get; set; }
public DateTime DateTime { get; set; }
public Customer Customer { get; set; }
public ICollection<OrderLine> OrderLines { get; set; }
}
public class OrderLine
{
public int Id { get; set; }
public Product Product { get; set; }
public int Price { get; set; }
public int Quantity { get; set; }
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public Category Category { get; set; }
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
}
I am using this infrastructure.
My aggregate roots are Customer, Order, Product. I did not include the mappings here as they are straight forward.
var customers = unitOfWork.Customers.FindAll();
var orders = unitOfWork.Orders.FindAll();
var products = unitOfWork.Products.FindAll();
var query = ......
Using LINQ, how would you select all customers that have orders for products in the "Beverages" category?
All samples I have seen on the web are very basic queries nothing advanced.
i found http://msdn.microsoft.com/en-us/vbasic/bb737909
May be your query should look like:
from c in unitOfWork.Customers
join o in unitOfWork.Orders on o.Customer = c
join ol in unitOfWork.OrderLines on ol.Order = o
where ol.Product.Category.Name == "Beverages"
select c
And it is necessary to add all parent-object-properties
This might work or not:
from customer in customers
where customer.Orders.Any(
o => o.OrderLines.Any(l => l.Product.Category.Name == "Beverages")
select customer
(I'm assuming you forgot the relationship between Product and Category)