S
S
stcmd042362016-06-18 10:40:33
C++ / C#
stcmd04236, 2016-06-18 10:40:33

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

3 answer(s)
S
Sanostee, 2016-06-18
@stcmd04236

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;
}

R
Roman, 2016-06-18
@yarosroman

Just like for any other class. metanit.com/sharp/tutorial/3.18.php

S
stcmd04236, 2016-06-18
@stcmd04236

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 question

Ask a Question

731 491 924 answers to any question