I am using the mongo driver for a API. The name of my db is "EventsDb". I need to insert an entity that I have and that is "Event". I need to return the last register of the mongo db:
T IRepository<T>.Add(T entity)
{
try
{
this.mongoCollection.InsertOne(entity);
var response = this.mongoCollection.Find<Event>("EventsDb").limit(1).sort();
return response;
}
catch (Exception e)
{
throw new NotImplementedException(e.ToString());
}
}
This is the problem I am having:
Severity Code Description Project File Line Suppression State
Error CS1929 'IMongoCollection' does not contain a definition for
'Find' and the best extension method overload
'IMongoCollectionExtensions.Find(IMongoCollection,
FilterDefinition, FindOptions)' requires a receiver of type
'IMongoCollection' Events.Repositories
How do I fix this error?
This is my solution for this problem I added a librarie
using MongoDB.Driver.Linq;
And after
public T Add(T entity)
{
try
{
this.mongoCollection.InsertOne(entity);
var response = this.mongoCollection.AsQueryable().OrderByDescending(c => c.Id).First();
return response;
}
catch (Exception e)
{
throw new NotImplementedException(e.ToString());
}
}
Related
I have a situation where I need to retrieve a particular document but I do not know it's PartitionKey.
The method looks like this:
public async Task<T> GetItemAsyncNoGroupId(string id)
{
try
{
Document document = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id),
new RequestOptions() { PartitionKey = new PartitionKey(Undefined.Value) });
return (T)(dynamic)document;
}
catch (DocumentClientException e)
{
if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}
else
{
throw;
}
}
}
I passed in the Undefined.Value to the PartitionKey object and that didn't work. I also didn't pass any PartionKey object into the ReadDocumentAsync method and that didn't work. I always get 'No Content' passed back. Any suggestions on how I can get this to work?
You need to use a cross partition query. Read about it here.
When calling for this function to create the database, an error occurs System.MissingMethodException: 'Method not found: int SQLite.SQLiteConnection.CreateTable(SQLite.CreateFlags)'
This is where it throws the error during the call for database = new TransmodLocalDB();
App.xaml.cs
public static TransmodLocalDB Database
{
get
{
if (database == null)
{
database = new TransmodLocalDB(0);
}
return database;
}
}
And here is the creation of the tables and the call could not proceed to here.
TransmodLocalDB.cs
public TransmodLocalDB()
{
try
{
database = DependencyService.Get<ISQLite>().GetConnection();
// create the tables
database.CreateTable<Account>(CreateFlags.None);
database.CreateTable<Driver>(CreateFlags.None);
database.CreateTable<Job>(CreateFlags.None);
database.CreateTable<TransportLeg>(CreateFlags.None);
database.CreateTable<Notes>(CreateFlags.None);
database.CreateTable<ImageNote>(CreateFlags.None);
database.CreateTable<Sync>(CreateFlags.None);
database.CreateTable<Enums>(CreateFlags.None);
} catch (Exception ex)
{
var me = ex.Message;
}
}
The exceptions throws before it can create the tables.
Used this library sqlite-net-pcl by Frank A. Krueger latest version 1.6.292
I have a lot of classes with this structure as you can see:
public class OrganizationUserRepository : IOrganizationUserRepository
{
private DataContext _ctx;
public OrganizationUserRepository(DataContext ctx)
{
_ctx = ctx;
}
public bool Add(OrganizationUser entity)
{
try
{
_ctx.OrganizationUsers.Add(entity);
_ctx.SaveChanges();
return true;
}
catch (Exception ex)
{
// TODO log this error
return false;
}
}
public bool Edit(OrganizationUser entity)
{
try
{
OrganizationUser Edited = _ctx.OrganizationUsers.Where(i => i.Id == entity.Id).First();
_ctx.Entry(Edited).CurrentValues.SetValues(entity);
_ctx.SaveChanges();
return true;
}
catch (Exception ex)
{
// TODO log this error
return false;
}
}
public bool Remove(string id)
{
try
{
Int64 Id = Int64.Parse(id);
OrganizationUser obj = _ctx.OrganizationUsers.Where(i => i.Id == Id).First();
_ctx.OrganizationUsers.Remove(obj);
_ctx.SaveChanges();
return true;
}
catch (Exception ex)
{
// TODO log this error
return false;
}
}
}
The db context in constructor is injected by ninject .as you can see it just one of my classes .and i have multi classes like this in another services that use a single DB .(WCF Service).But i get this error in my wcf tracelog :
ExecuteReader requires an open and available Connection. The connection's current state is open.
I am using EF code first .
I found this Wrap DbContext db = new DbContext() inusing statement. And i want to know should i use this ,if Yes how can i change my class structure to use using in my code ?
I used public Readonly DbContext .i just remove readonly and everything work fine.
In my code I save a lot of classes to the database over and over using the same methodology. So I tried to abstract it, shown below:
public long Save<T>(BaseViewInterface<T> view, AppsRTSEntities dbContext)
{
try
{
if (view.IsNew())
{
return Create(view, dbContext);
}
else
{
T tmp = view.ToPersistent(dbContext);
dbContext.T.Attach(tmp);
dbContext.Entry(tmp).State = System.Data.Entity.EntityState.Modified;
dbContext.SaveChanges();
return tmp.ID;
}
}
catch (DbEntityValidationException exc)
{
throw new DbEntityValidationException(GetExceptionMsg(exc), exc);
}
catch (DbUpdateException exc)
{
throw new DbEntityValidationException(GetExceptionMsg(exc), exc);
}
}
T is the autogenerated partial class Microsoft creates. So for instance my view would be
public class MyView : BaseViewInterface<My>
My would be the auto-generated class that is created as part of the db context. So my question is simple. What am I doing wrong here? How can I make this generic saving work?
Edit: I can't just modify AppsRTSEntities to include a definition for T, as it's also auto-generated.
Intstead of doing dbContext.T.Attach(tmp); you need to use the DbContext.Set<T>() method to get the generic DbSet datatype.
else
{
T tmp = view.ToPersistent(dbContext);
//Could also do "dbCondext.Set<T>().Attach(tmp);" but I split it for this example
DbSet<T> t = dbCondext.Set<T>();
t.Attach(tmp);
dbContext.Entry(tmp).State = System.Data.Entity.EntityState.Modified;
dbContext.SaveChanges();
return tmp.ID;
}
I´m currently developing an iOS App with Xamarin and ran into a strange error with sqlite-net-pcl:
{SQLite.SQLiteException: near ")": syntax error at SQLite.SQLite3.Prepare2 (SQLitePCL.sqlite3 db, System.String query) [0x0001e] in <49ac49cfb94341128f6929b3ff2090ee>:0 at SQLite.PreparedSqlLiteInsertCommand.Prepare () [0x00011] in <49ac49cfb94341128f6929b…}
The error occours when I want to insert into a table of the following model:
public class PPPCount
{
public PPPCount()
{
}
[PrimaryKey]
public int Id { get; set; }
public string PerpePartCount { get; set; }
}
Here is the calling code:
try
{
var con = await DbFactory.Instance();
var perpetrationPartCount = await
service.GetSumPerpetrationParts(immobilePerpetrationId);
var dbModel = await con.FindAsync<PPPCount>(immobilePerpetrationId);
if (dbModel == null)
{
var model = new PPPCount();
model.Id = immobilePerpetrationId;
model.PerpePartCount = perpetrationPartCount;
//This causes the exception!!!!
await con.InsertAsync(perpetrationPartCount);
}
else
{
if (dbModel.PerpePartCount != perpetrationPartCount)
{
dbModel.PerpePartCount = perpetrationPartCount;
await con.UpdateAsync(dbModel);
}
}
return perpetrationPartCount;
}
catch (Exception e)
{
//AlertHelper.ShowError(e.Message);
}
The code of the DbFactory that creates and holds my sqlite connection object:
public class DbFactory
{
private static SQLiteAsyncConnection connection;
public static async Task<SQLiteAsyncConnection> Instance()
{
if (connection == null)
{
bool deleteDb = false;
string folder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var dbPath = System.IO.Path.Combine(folder, "..", "immotech_offline.db3");
if (File.Exists(dbPath) && deleteDb)
{
File.Delete(dbPath);
}
connection = new SQLiteAsyncConnection(dbPath);
try
{
await connection.CreateTableAsync<ImmobilePerpetration>();
await connection.CreateTableAsync<Customer>();
await connection.CreateTableAsync<PPPCount>();
}
catch (Exception e)
{
//TODO: Delete this part!
int i = 0;
}
}
return connection;
}
}
The strange thing is I can work with the two other models without any problems!
I really can´t explain what is causing this error and I tried to enable the tracing to show the SQL-Statements, but unfortunatelly the Async version of the sqlite connection object doesn´t provide a tracing.
Then I tried the same code in synchronous version with tracing enabled and this is the result:
insert into "Int32"() values ()
Well this is very clear why it isn´t working, but how can such a statement be generated? Did I missed something or it is a bug?
UPDATE: Yes I used the search function and no case fits for my problem.
Should this:
await con.InsertAsync(perpetrationPartCount);
be:
await con.InsertAsync(model);
We can't tell what type perpetrationPartCount is based on your code. It might not be a PPPCount and therefore that entity might not be the issue.