Currently, when using LINQ, cannot add an entity with a key that is already in use (you cannot add an object whose key is already in use .). Error. I did not find the reason after searching for the Internet for a long time, so I finally solved the problem through patient analysis and testing, but I still don't know why, maybe I don't know about the LINQ mechanism.
First, let's talk about the cause: when the data access definition uses the singleton mode (that is, the method is not commented out), it will always appear: "Cannot add an entity with a key that is already in use. "The operation is successful once after IIS is restarted occasionally. If the data access definition adopts the general method, this error will not occur and you do not know why. Will other databases have such problems? Is there such a problem in the winform program.
Database: SQLite
Data Table: tab_advice, which records user suggestions
Orm is defined as follows:
[Table (name = "tab_advice")] <br/> public class tab_advice <br/>{< br/> [column (isprimarykey = true)] <br/> Public string name; </P> <p> [column] <br/> Public String unit; </P> <p> [column] <br/> Public String touch; </P> <p> [column] <br/> Public String content; </P> <p> [column] <br/> Public String IP; </P> <p >}< br/>
Data access is defined as follows:
Public class serverdatacontext {<br/> // public static readonly serverdatacontext instance; </P> <p> private table <tab_advice> advices; </P> <p> private datacontext dB; </P> <p> // static serverdatacontext () {<br/> // instance = new serverdatacontext (); <br/> //} </P> <p> Public serverdatacontext () {<br/> DB = new datacontext (New sqliteconnection ("Data Source =" + httpcontext. current. server. mappath ("~ /App_data/server. db3 "); <br/> This. advices = This. DB. gettable <tab_advice> (); <br/>}</P> <p> Public void saveadvice (tab_advice tab) {<br/> This. advices. insertonsubmit (Tab); <br/> This. DB. submitchanges (); <br/>}< br/>}
The usage is as follows:
[Webmethod] <br/> Public bool sendmessage (string name, string unit, string touch, string message) {<br/> tab_advice tab = new tab_advice (); <br/> tab. name = Name; <br/> tab. unit = unit; <br/> tab. touch = touch; <br/> tab. content = message; <br/> tab. IP = context. request. userhostaddress; <br/> try {<br/> serverdatacontext DB = new serverdatacontext (); <br/> dB. saveadvice (Tab); <br/> return true; <br/>}catch {<br/> return false; <br/>}< br/>}