This method will help to get the key exists or not from an entityset in EntityFramework
Here
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;
try
{
string entitySetName = Enum.GetName(typeof(TargetTable), tableName);
var primaryKeyName = objDb
.MetadataWorkspace
.GetEntityContainer(objDb.DefaultContainerName, System.Data.Metadata.Edm.DataSpace.CSpace)
.BaseEntitySets
.First(meta => meta.ElementType.Name == entitySetName)
.ElementType
.KeyMembers
.Select(k => k.Name)
.FirstOrDefault();
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;
}
Here
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;
try
{
string entitySetName = Enum.GetName(typeof(TargetTable), tableName);
var primaryKeyName = objDb
.MetadataWorkspace
.GetEntityContainer(objDb.DefaultContainerName, System.Data.Metadata.Edm.DataSpace.CSpace)
.BaseEntitySets
.First(meta => meta.ElementType.Name == entitySetName)
.ElementType
.KeyMembers
.Select(k => k.Name)
.FirstOrDefault();
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