简体   繁体   中英

C# - Entity Framework inserting

I have two tables Category and Product and I would like to insert products into categories. The table relation between these tables is one to zeor or one.

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? How do I handle the foriegn key situation? If the categoryid does not exists then the product should not be inserted.

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:

http://msdn.microsoft.com/en-us/library/bb425822.aspx

Linq to Sql 101

Learn the Entity Framework

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. If you don't have one please specify more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM