Answer the question
In order to leave comments, you need to log in
How to write a method extension for EF6?
Good afternoon! How can I write an extension for entity framework 6 methods? Or is there any solution for similar requests.
Answer the question
In order to leave comments, you need to log in
Implement the IEntity interface for the model to use the generic type constraint in the extension method:
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;
}
Roman wrote the following, but it turns out these generic types do not work with value types. It remains only the option of expression trees, but I just can not understand these trees.
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;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question