Ben Adams
Ben Adams

Reputation: 564

Entity Framework auto generates IDs even though I specify my own

I have a SQL DB with a table called Node. It has a combined key: NodeId, DocId. Both columns are set to Identity specification = No. I generated an EDMX in Visual Studio to save Nodes to the DB from EF. The Node object that VS generated has the two fields set to StoreGeneratedPattern = None. The NodeId that I specify is correctly put in the DB, but the DocId is autogenerated. Every time I insert some new Nodes they all get the same DocId. This is correct, however it's not the DocId that I specified in my object. It's an autogenerated one. The NodeId that I specify is saved correctly to the DB - this field doesn't get autogenerated. I don't see any differenc between the two fields.

Here's my code:

using (MyEntities db = new MyEntities())
{
    // Delete old nodes using my own extension method
    db.DeleteObjects(db.Nodes.Where(n => n.DocId == doc.DocId));

    // Create EF doc object
    Document newDbDoc = docDTO.ToDbDoc();

    // Add new nodes using my own extension method
    db.Nodes.AddObjects(newDbDoc.Nodes);

    try
    {
        db.Connection.Open();

        using (var transaction = db.Connection.BeginTransaction())
        {
            try
            {
                db.SaveChanges();

                transaction.Commit();

                return Json("Success");
            }
            catch
            {
                transaction.Rollback();

                return Json("Error");
            }
        }
    }
    catch
    {
        return Json("Error");
    }
}

My own extension methods:

public static class ObjectContextExtensions
{
    public static void DeleteObjects(this ObjectContext context, IEnumerable<EntityObject> entities)
    {
        foreach (var ent in entities)
        {
            context.DeleteObject(ent);
        }
    }

    public static void AddObjects<TEntity>(this ObjectSet<TEntity> objectSet, IEnumerable<TEntity> entities) where TEntity : class
    {
        foreach (var ent in entities)
        {
            objectSet.AddObject(ent);
        }
    }
}

What am I doing wrong?

Upvotes: 0

Views: 211

Answers (1)

Ben Adams
Ben Adams

Reputation: 564

Ack... I found out what was happening. Every time I added the nodes a new Document was created in the Document table even though I never added the survey object. I guess EF is "smart" enough to create the Document itself because the Nodes each has a reference to the survey. I solved it by only creating a list of nodes with a reference to an existing DocId and not including the Document object itself.

Upvotes: 1

Related Questions