I am new to EF and am having trouble deserializing an object and then putting it back in the SQL Server Express (2014) DB . For this demo, I have just two tables, "Patient" and "Session". A Patient has 0 or more Sessions. The idea is to allow the user to export a session to disk. At some later point, he may want to put it back in the DB.
I've put my code below. I create 2 entities (Patient and Session), save them to DB. I checked that they are there. I then serialize the Session, and then remove the Session. I then (successfully) deserialize the session. I then call:
context2.Sessions.Add(session2);
context2.SaveChanges();
On the SaveChanges line I get an exception informing me that:
System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'PK_Patient'. Cannot insert duplicate key in object 'dbo.Patient'. The duplicate key value is (9749184b-380b-438a-a2fe-80413c3a616a).
Can someone tell me what I'm doing wrong? Should I be using 'Attach' instead of 'Add'? It sure looks like it's trying to recreate the Patient entry. Ideally, if it's saved to a Database that already has that particular Patient (as decided by primary key PatientGUID), it should use that. If there is not Patient with that PatientGUID, it should create one. Can someone get me going? If I can provide more info, or info in a different form, please let me know.
I've posted code and table layout below.
Thanks, Dave
static void Main(string[] args)
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
using (PlayContext context = new PlayContext())
{
try
{
Patient pt = new Patient();
Guid ptGuid = Guid.NewGuid();
pt.PatientGUID = ptGuid;
pt.PatientNumber = 1;
Session session = new Session();
session.SessionGUID = Guid.NewGuid();
session.SessionNum = 101;
pt.Sessions.Add(session);
context.Patients.Add(pt);
context.SaveChanges();
try
{
formatter.Serialize(stream, session);
}
catch (Exception ex)
{
int x = 1;
}
context.Sessions.Remove(session);
context.SaveChanges();
}
catch (Exception ex)
{
}
}
using (PlayContext context2 = new PlayContext()) // I use a new context as we'd often be getting entity back from file weeks later and from different program
{
try
{
stream.Seek(0, SeekOrigin.Begin);
Session session2 = (Session)formatter.Deserialize(stream);
context2.Sessions.Add(session2);
context2.SaveChanges();
}
catch (Exception ex)
{
}
}
}
For the two tables, I have
Patient Table
PatientGUID uniqueidentifier NOT Allow Nulls Primary Key
PatientNumber int NOT Allow Nulls
Session Table
SessionGUID uniqueidentifier NOT Allow Nulls Primary Key
PatientGUID uniqueidentifier NOT Allow Nulls (foreign key to PatientGUID in patient table)
SessionNum int NOT Allow Nulls
Insert and Update Specific for Session Table are set to 'Cascade'