I am trying to convert the following LLBLGEN statement to FetchEntityCollectionAsync using QueryParameters...
adapter.FetchEntityCollection(templateEntities,
new RelationPredicateBucket(
new PredicateExpression(
TemplateFields.TemplateTypeId == (int)templateType)));
I have constructed the following statement but not sure how to implement RelationPredicateBucket from above.
var queryParam = new QueryParameters
{
CollectionToFetch = templateEntities,
FilterToUse = new PredicateExpression(TemplateFields.TemplateTypeId == (int)templateType)
};
await adapter.FetchEntityCollectionAsync(queryParam, CancellationToken.None);
What do I need to do?
Related
I want to find a role details with specified username in MongoDb with Drivers in C#.
I don't want to use any builders or linq methods.
I tried this to insert a Bson document and it worked.
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("test");
var collec = database.GetCollection<BsonDocument>("user");
var documnt = new BsonDocument{
{"username", txtUsername.Text},
{"password", txtPassword.Password}
};
var check_count = collec.CountDocuments(documnt);
But when I tried this code to find a role with username its not working:
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("test");
var collec = database.GetCollection<BsonDocument>("user");
var documnt = new BsonDocument{
{"username", "admin"},
{"role", 1}
};
var role = collec.Find(documnt);
txtTestRole.Text = role.ToString();
I got this as output:
enter image description here
You have to materialize the query.
As you query for single record, you can use IAsyncCursorSourceExtensions.SingleOrDefault Method.
Or you can refer to IFindFluent (Extension methods section) to select the method that is best suited to you.
Next, from returned BsonDocument to select the specific field for the displayed value.
var user = collec.Find(documnt)
.SingleOrDefault();
if (user == null)
{
// Handle user not exist
return;
}
txtTestRole.Text = user["role"].ToString();
I have a list of objects with various properties. I want to query a database using these properties and get a result list back.
This is what I've tried:
public async Task<IEnumerable<Animal>> GetAnimalsFromAttributesAsync(IEnumerable<AnimalInfo> attributeSets)
{
using (var myDB = new SqlConnection(connectionString))
{
await myDB.OpenAsync();
var results = new List<Animal>();
foreach (var attributeSet in attributeSets)
{
var sql = #"select AnimalID, AnimalTypeID, AnimalColor
from Animals
where AnimalTypeID = #AnimalTypeID
and AnimalColorID = #AnimalColorID";
var result = myDB.Query<Animal>(sql, attributeSet);
results.AddRange(result);
}
return results
}
}
This works ok for small numbers of properties. But if I have a lot of properties, then I get this error:
Error: The incoming request has too many parameters. The server supports a maximum of 2100 parameters. Reduce the number of parameters and resend the request.
Is there a better way to do this?
Thanks to #MarcGravell's suggestion, I decided to rewrite my query as a TVP query.
SQL:
create type AnimalInfo as table
(
AnimalTypeID int,
AnimalColorID int
)
go
C#:
public async Task<IEnumerable<Animal>> GetAnimalsFromAttributesAsync(DataTable attributeSets)
{
using (var myDB = new SqlConnection(connectionString))
{
await myDB.OpenAsync();
var sql = #"select AnimalID, AnimalTypeID, AnimalColor
from Animals
inner join #animalInfos animalInfos on
animalInfos.AnimalColorID = Animals.ColorID
and
animalInfos.AnimalTypeID = Animals.AnimalTypeID";
var result = await myDB.QueryAsync<Animal>(sql, new { animalInfos = attributeSets.AsTableValuedParameter("AnimalInfo") };
return result;
}
}
i am trying to find documents in collection by ids. Most of the suggested answers use C# class that matches with the document. something like here
var filter = Builders<Product>.Filter
.In(p => p.Id, productObjectIDs);
i don't have corresponding C# class, so i am using BsonDocument
public async Task<IEnumerable<BsonDocument>> GetData(IEnumerable<int> documentIds)
{
var collection = _mongoDatabase.GetCollection<BsonDocument>("mycollection");
// how do set filter here
var filterBuilder = Builders<BsonDocument>.Filter.In<int>("???????", documentIds);
var projection = Builders<BsonDocument>.Projection
.Include("_id")
.Include("status")
.Include("units");
var result = await collection.Find(filterBuilder).Project<BsonDocument>(projection).ToListAsync().ConfigureAwait(false);
return result;
}
I am not sure how do i set filter with in operator?
You may try this filter:
var filter = new BsonDocument("_id", new BsonDocument("$in", new BsonArray(documetIds)));
Based on this answer
This is my code:
var database = new MongoClient("mongodb://192.168.3.122").GetDatabase("xxxx");
var collection = database.GetCollection<School>("School");
//var it = new List<IMongoQuery>();
//it.Add(Query.EQ("Phone", "77915656"));
//it.Add(Query.EQ("EstablishedYear", 1349));
//var query = new QueryBuilder<School>();
//query.And(it);
IMongoQuery query = new QueryDocument();
Query.And(query, Query.EQ("Phone", "77915656"));
Query.And(query, Query.EQ("EstablishedYear", 1349));
collection.Find(query).ToList(); // eror here!!!
I don't know how to get result from query?!
And error is:
'MongoDB.Driver.IMongoCollection' does not contain a definition for 'Find' and the best extension method overload 'MongoDB.Driver.IMongoCollectionExtensions.Find(MongoDB.Driver.IMongoCollection, MongoDB.Driver.FilterDefinition, MongoDB.Driver.FindOptions)' has some invalid arguments
Your QueryDocument does not contain the type, which Find requires... if you want to create a filter, use a filter builder... out of my mind:
var database = new MongoClient("mongodb://192.168.3.122").GetDatabase("xxxx");
var collection = database.GetCollection<School>("School");
var builder = Builders<School>.Filter;
var filter = builder.Eq("Phone", "77915656");
filter = filter & builder.Eq("EstablishedYear", 1349);
var myFilteredList = collection.Find(filter).ToList();
I'm using the MongoDB .Net driver in my project. I want to update all of the properties of my object that is stored in MongoDB. In the documentation, update is shown like this:
var filter = Builders<BsonDocument>.Filter.Eq("i", 10);
var update = Builders<BsonDocument>.Update.Set("i", 110);
await collection.UpdateOneAsync(filter, update);
But I don't want to call the Set method for all of the properties, since there are many properties and can be many more in the future.
How can I update the whole object using the MongoDB .Net driver?
You can do that with ReplaceOneAsync instead of UpdateOneAsync.
You need a filter to match the existing document (a filter with the document id is the simplest) and the new object.
Hamster hamster = ...
var replaceOneResult = await collection.ReplaceOneAsync(
doc => doc.Id == hamster.Id,
hamster);
var update = new BsonDocument("$set", new BsonDocument(entityType.GetProperties().Where(p => p.Name != "Id").Select(p => new KeyValuePair<string, object>(p.Name, entityType.GetProperty(p.Name).GetValue(task, null)))));
var options = new UpdateOptions();
collection.UpdateOne<MyTask>(item => item.Name == "cheque", update, options);
this code uses reflection to include all properties of the given object
to the update statement, no need to manually add all properties, as u see the Id is explicitly excluded from the update statement to avoid exception.
If you want to update your whole BsonDocument, there is an implicit conversion from BsonDocument to UpdateDefinition.
https://github.com/mongodb/mongo-csharp-driver/blob/master/src/MongoDB.Driver/UpdateDefinition.cs
var doc = new BsonDocument() { .... }
UpdateDefinition<BsonDocument> update = doc;