私はc#とef4を使用しています。
私は2つのプロパティを持つエンティティを持つモデルを持っていint Id
ますstring Title
.
Id と Title が DataSource に存在ESQL
する場合に実行できるクエリを作成する必要があります。return bool TRUE
Id はデータ ストレージの PrimaryKey であることに注意してください。
それを行う方法はありますか?
私はc#とef4を使用しています。
私は2つのプロパティを持つエンティティを持つモデルを持っていint Id
ますstring Title
.
Id と Title が DataSource に存在ESQL
する場合に実行できるクエリを作成する必要があります。return bool TRUE
Id はデータ ストレージの PrimaryKey であることに注意してください。
それを行う方法はありますか?
以下の各コードスニペットでそれを行うことができます:
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は私があなたに提案する最良の方法です。良いロック
javadが言ったことは真実ですが、別の方法は次のとおりです。
bool result = entities.Any(x=>x.Id == id && x.Title == title) ;
実は Id は主キーなので、DB はこれが複数回発生するのを防ぎます。