public interface IEntity
{
int Id { get; set; }
}
public class Model : IEntity
{
public int Id { get; set; }
// ...
}
public static bool ExistById<T>(this DbSet<T> source, int id) where T : IEntity
{
return source.Count(c => c.Id == id) > 0;
}
public static bool ExistById<T> (this DbSet<T> source, int Id)
{
string sql = source.ToString();
var regex = new Regex("FROM (?<table>.*) AS");
var match =regex.Match(sql);
var tableName = match.Groups["table"].Value;
string query = string.Format("SELECT [dbo].[{0}].[Id] FROM [dbo].[{0}] WHERE [dbo].[{0}].[Id] == {1}", tableName, Id.ToString());
var result = source.SqlQuery(query).FirstOrDefault();
return result != null ? true : false;
}