views:

70

answers:

0

Hello,

I am using a generic code for my repositories on top of entity framework v2:

    public virtual void Save(T entity)
    {
        using (C context = new C())
        {
            string entitySetName = context.FindEntitySetByEntity<T>();

            T entityInDDBB = GetEntityByKey(entity, entitySetName, context);

            //if we didn't find the entity in database make an insert, if not an update.
            if (entityInDDBB == null)
            {
                context.AddObject(entitySetName, entity);
            }
            else
            {
                context.ApplyCurrentValues(entitySetName, entity);
            }



            context.SaveChanges();
        }
    }

But if I insert (entityInDDBB==null branch) an Entity related to another and this second entity exists in DDBB it throws a PK exception.

How could I check if related entities exists in DDBB?

Thanks in advance.