[英]C# - Entity Framework inserting
I have two tables Category and Product and I would like to insert products into categories. 我有两个表Category和Product,我想将产品插入类别。 The table relation between these tables is one to zeor or one. 这些表之间的表关系是zeor或1。
Category table: 类别表:
CID : integer,
CategoryName : varchar,
Product table: 产品表:
CID: integer, // foreign key to category table.
ProductName: varchar,
UnitsInstock: integer,
How can I write a simple query for inserting a product into the ProductTable? 如何编写一个简单查询以将产品插入ProductTable? How do I handle the foriegn key situation? 如何处理外键关键情况? If the categoryid does not exists then the product should not be inserted. 如果categoryid不存在,则不应插入产品。
I would realy appreciate any kinds of help. 我真的很感谢任何帮助。
Normally a category to product would be many to one, but I would suggest studying the basics of Linq to Sql first: 通常,产品的类别是多对一的,但我建议您首先研究Linq to Sql的基础知识:
http://msdn.microsoft.com/en-us/library/bb425822.aspx http://msdn.microsoft.com/en-us/library/bb425822.aspx
One approach could be this one: 一种方法可能是这种方法:
int categoryIdOfNewProduct = 123;
using (var context = new MyContext())
{
bool categoryExists = context.Categories
.Any(c => c.Id == categoryIdOfNewProduct);
if (categoryExists)
{
var newProduct = new Product
{
Name = "New Product",
CategoryId = categoryIdOfNewProduct,
// other properties
};
context.Products.Add(newProduct); // EF 4.1
context.SaveChanges();
}
else
{
//Perhaps some message to user that category doesn't exist? Or Log entry?
}
}
It assumes that you have a foreign key property CategoryId
on your Product
entity. 假定您在Product
实体上具有外键属性CategoryId
。 If you don't have one please specify more details. 如果您没有,请指定更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.