TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Samio
NA
201
176.5k
Adding new child record to binding source using Entity Framework
Jun 19 2012 8:39 AM
Hi all,
Having 1 winForm with 2 grids bound to bindingsource controls: 1 grid for categories (master) and 1 grid for Products (detail) , data and relationship are well loaded.
Now, I try to add a new (master) record to categories:
For the next two cases I get issues:
First case: When I click "+" button without entering anything " New Category" is not added and I gat the message: "Cannot insert the value NULL into column 'CategoryName', table 'Northwind.dbo.Categories'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated." spite of filling it by code.
Second case: When I click "+" button and enter manually something in the CategoryName cell, after clicking save button it is persisted, but I get the message: "The changes to the database have been validated, but an error has occurred while updating the object context. ObjectContext might be in an inconsistent state. Internal exception message: AcceptChanges can not continue because the key values of the object are in conflict with another object in ObjectStateManager. Make sure key values are unique before calling AcceptChanges".
Here is my code:
namespace MyNameSpace
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
NorthwindEntities ctx;
bool _adding;
private void Form2_Load(object sender, EventArgs e)
{
ctx = new NorthwindEntities();
categoriesBindingSource.DataSource = ctx.Categories;
}
private void categoriesBindingSource_AddingNew(object sender, AddingNewEventArgs e)
{
_adding = true;
}
private void categoriesBindingSource_CurrentChanged(object sender, EventArgs e)
{
if (_adding)
{
categoriesBindingSource.EndEdit();
var newCat = (Categories)categoriesBindingSource.Current;
if (newCat.Products == null)
{
Products Prd = new Products();
Prd.Discontinued = false;
Prd.ProductName = "New Product Name";
ctx.AddToProducts(Prd);
}
newCat.CategoryName = " New Category";
ctx.AddToCategories(newCat);
_adding = false;
}
}
private void categoriesBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
categoriesBindingSource.EndEdit();
ctx.SaveChanges();
}
Please any help ?
Reply
Answers (
4
)
how to count time user stays on web page?
How to recover a table?