views:

46

answers:

4

I don't know why it's is error on SaveChanges(), i search in google, some body say using EF, the database's table such have primary key, i have this, but still error. The error message is not enough clear,it just throws System.Data.UpdateException. The Code:

public static void AddAccount(int _acc_id,string _name)
{
    dataEntities de = new dataEntities(GetEntityConn());
    account acc = new account
    {
        account_id = _acc_id,
        name =  _name
    };
    de.AddObject("account", acc);
    de.SaveChanges();
}
A: 

My psychic powers tell me that the account_id field has a unique constraint on it and that the value of _acc_id is already in the table.

If my mighty psychic powers are wrong, then more information is required. 8 )

Task
The table have 2 column, account_id and name , I have remove the account_id = acc_id now,the account_id the auto-increment,because i read (SQL CE, when used with EF4, does not support autogenerated primary keys : http://social.msdn.microsoft.com/forums/en-US/sqlce/thread/48984bd4-0921-4637-bd8f-8aa1ae9514ab/) now i just insert name, but still not work :(
SilverNight
Perhaps use a stored procedure to do the Add passing in just the name and use EF to call the stored procedure? That might be a good implementation.
Task
A: 

Guessing that the EntitySetName isn't called account, but that's hard to tell without more information.

What I would do is something like:

public static void AddAccount(int _acc_id,string _name)
{
    dataEntities de = new dataEntities(GetEntityConn());
    account acc = new account
    {
        account_id = _acc_id,
        name =  _name
    };
    de.Accounts.Add(acc);
    de.SaveChanges();
}

This gets rid of the string value, so it should also help refactoring

Sander Rijken
I open the *.edmx to see, the entity set name is really "account" :(However,and there is no "Add" method, here the screen-shothttp://www.imgxc.com/fullimage/qNzIWp.png
SilverNight
it's not AccountSet?
Jeroen
What type is `de.account`?
Sander Rijken
A: 

Update: I have tried create a same table on SQL Server 2008, generate edmx file from that, and use same code for insertion,it works! So i believe it all about EF 4.0 with SQLCE.... I upload a test project in window form , with a SQLCE database , and with one button event, you can download on

http://www.netfrd.com/testproject.zip

The code is very simple ,but it really not work.

SilverNight
+2  A: 

Solved : I found the solution, see this thread : http://social.msdn.microsoft.com/Forums/en-US/sqlce/thread/48984bd4-0921-4637-bd8f-8aa1ae9514ab For short, don't use int as datatype , use uniqueidentifier type.This problem will not happen on SQL Server, it only occur when using SQLCE.

SilverNight