How to return a Bool from a Where Filter using Entity Framework and Esql

StackOverflow https://stackoverflow.com/questions/7537356

  •  27-01-2021
  •  | 
  •  

Question

I use c# and ef4.

I have a Model with an Entity with two proprieties int Id and string Title.

I need to write an ESQL query that is able to return bool TRUE if Id and Title are present in the DataSource. Please note Id is a PrimaryKey in my data storage.

Any idea how to do it?

Était-ce utile?

La solution

You can do it by each code-snippets below:


1)

using (YourEntityContext context = new YourEntityContext ()) {
    var queryString = 
        @"SELECT VALUE TOP(1) Model FROM YourEntityContext.Models 
              As Model WHERE Model.Id = @id AND Model.Title = @title";
    ObjectQuery<Model> entityQuery = new ObjectQuery<Model>(queryString, context);
    entityQuery.Parameters.Add(new ObjectParameter("id", id));
    entityQuery.Parameters.Add(new ObjectParameter("title", title));
    var result = entityQuery.Any();
}

2)

using (YourEntityContext context = new YourEntityContext ()) {
    ObjectQuery<Model> entityQuery = 
        context.Models
        .Where("it.Id = @id AND it.Title = @title"
            , new ObjectParameter("id", id)
            , new ObjectParameter("title", title)
        );
    var result = entityQuery.Any();
}

3)

var context = new YourEntityContext();
using (EntityConnection cn = context.Connection as EntityConnection) {
    if (cn.State == System.Data.ConnectionState.Closed)
        cn.Open();
    using (EntityCommand cmd = new EntityCommand()) {
        cmd.Connection = cn;
        cmd.CommandText = @"EXISTS(
                                SELECT M FROM YourEntityContext.Models as M 
                                WHERE M.Id == @id AND Model.Title = @title
                           )";
        cmd.Parameters.AddWithValue("id", _yourId);
        cmd.Parameters.AddWithValue("title", _yourTitle);
        var r = (bool)cmd.ExecuteScalar();
    }
}

4)

using (YourEntityContext context = new YourEntityContext ()) {
    var queryString = 
        @"EXISTS(
              SELECT M FROM YourEntityContext.Models as M 
              WHERE M.Id == @id AND Model.Title = @title
          )";
    ObjectQuery<bool> entityQuery = new ObjectQuery<bool>(queryString, context);
    entityQuery.Parameters.Add(new ObjectParameter("id", id));
    entityQuery.Parameters.Add(new ObjectParameter("title", title));
    var result = entityQuery.Execute(MergeOption.AppendOnly).FirstOrDefault();
}

4 is the best way I suggest you. Good lock

Autres conseils

What javad said is true, but another way is:

bool result = entities.Any(x=>x.Id == id && x.Title == title) ; 

In fact because Id is primary key, DB prevent from occurrence of this more than one time .

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top