Tuesday, April 10, 2012

How to check the Key exists or not in EntityFramework C#?

This method will help to get the key exists or not from an entityset in EntityFramework
TargetTable is the Enum where I have all the tables names
string keyValue is the value for which i am checking exists or not

 public bool CheckKey(TargetTable tableName, string keyValue, MyMotorEntities objDb)
bool isKeyAlreadyExists = false;
                                string entitySetName = Enum.GetName(typeof(TargetTable), tableName);
                                var primaryKeyName = objDb
   .GetEntityContainer(objDb.DefaultContainerName, System.Data.Metadata.Edm.DataSpace.CSpace)
   .First(meta => meta.ElementType.Name == entitySetName)
   .Select(k => k.Name)
                                List<KeyValuePair<string, object>> lstEnum = new List<KeyValuePair<string, object>>();
                                lstEnum.Add(new KeyValuePair<string, object>(primaryKeyName, keyValue));
                                var lsttype = from t in lstEnum select t;
                                IEnumerable<KeyValuePair<string, object>> IeList = ((IEnumerable<KeyValuePair<string, object>>)lsttype).Select(x => x).AsQueryable();
                                System.Data.EntityKey key = new System.Data.EntityKey("MyMotorEntities." + entitySetName , IeList);
                                var tbl = objDb.GetObjectByKey(key);
if (tbl!=null)
                    isKeyAlreadyExists = true;
                            catch (Exception ex)

 return isKeyAlreadyExists;

No comments:

Post a Comment