0

我使用 c# 和 ef4。

我有一个带有两个属性的实体的模型int Idstring Title.

如果 Id 和 Title 存在于 DataSource 中,我需要编写一个ESQL查询。return bool TRUE请注意 Id 是我的数据存储中的 PrimaryKey。

知道怎么做吗?

4

2 回答 2

5

您可以通过下面的每个代码片段来做到这一点:


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是我建议你的最好方法。好锁

于 2011-09-24T06:26:28.990 回答
2

javad 说的是真的,但另一种说法是:

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

事实上,因为 Id 是主键,所以 DB 可以防止这种情况发生不止一次。

于 2011-09-24T06:39:26.960 回答