.NET Core MongoDB. Find by guid returns null - mongodb

I have the following setup:
The document:
[BsonCollection("Users")] // I get the collection name with a custom extension
[BsonIgnoreExtraElements]
public class UserDocument
{
[BsonId]
public Guid Id { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public UserSettingsModel UserSettings { get; set; }
}
public class UserSettingsModel
{
// ...
}
The repository:
public class UserRepository
{
private readonly IMongoCollection<UserDocument> _collection;
private readonly ILogger<UserRepository> _logger;
public UserRepository(IMongoDatabase database, ILogger<UserRepository> logger)
{
// returns "Users"
var collectionName = typeof(UserDocument).GetCollectionName();
_collection = database.GetCollection<UserDocument>(collectionName);
}
// ...
public async Task<UserDocument> GetById(Guid id)
{
var filter = Builders<UserDocument>.Filter.Eq(x => x.Id, id);
var user = await _collection.FindAsync(filter);
// var user = await _collection.FindAsync(x => x.Id == id); - doesn't work either
var request = filter.Render(
_collection.DocumentSerializer,
_collection.Settings.SerializerRegistry).ToString();
_logger.LogDebug(request);
return user.FirstOrDefault();
}
}
And I initialize the client this way:
// ...
BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));
var client = new MongoClient(connectionString);
var database = client.GetDatabase(dbName);
services.AddSingleton(c => database);
// convention pack and registries
// ...
// if moved here doesn't work either
// BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));
The filter generated in GetById is still the following: { "_id" : CSUUID("459f165a-4a91-4f39-906c-dc7401ee2468") } when I expect it to be UUID instead of CSUUID.
So, the query doesn't find anything and returns null. In the database the document I'm searching for has _id: UUID('459f165a-4a91-4f39-906c-dc7401ee2468')
What am I doing wrong?

I was able to fixing by this trick:
var mongoConnectionUrl = new MongoUrl(connectionString);
var mongoClientSettings = MongoClientSettings.FromUrl(mongoConnectionUrl);
// before initializing client
mongoClientSettings.GuidRepresentation = GuidRepresentation.Standard;
However setting the GuidRepresentation in client settings is obsolete, which is quite confusing. Also, the query generated still has CSUUID instead of UUID. I was able to log the query the following way:
mongoClientSettings.ClusterConfigurator = cb =>
{
cb.Subscribe<CommandStartedEvent>(e => logger.LogDebug($"{e.CommandName} - {e.Command.ToJson()}"));
};
If anyone finds a better way and post it here it would be appreciated.

Related

An error occurred while updating the entries

I'm strugglish with adding feature for my controller. While adding new item, receving the error like: "An error occurred while updating the entries. See the inner exception for details."
I debugged it, and understood ProductDetailIs is null and here is the issue. But, can not figure out how to mend the problem.
Here is the DTO models:
public class WishlistItemDto
{
public int Id { get; set; }
public string CustomerId { get; set; }
public ProductDetailsDtoWithPrimaryImage ProductDetails { get; set; }
public int Quantity { get; set; }
}
public class WishListItemCreationDto
{
public string CustomerId { get; set; }
public int ProductDetailId { get; set; }
public int Quantity { get; set; }
}
Controller:
[HttpPost]
public async Task<IActionResult> Add(WishListItemCreationDto wishListItemDto)
{
var itemAdd = _mapper.Map<WishlistItemDto>(wishListItemDto);
var itemCreated = await _wishListItemService.AddAsync(itemAdd);
return CreatedAtAction(nameof(GetId), new { id = itemCreated.Id }, wishListItemDto);
}
Service:
public async Task<WishlistItemDto> AddAsync(WishlistItemDto item)
{
var entity = _mapper.Map<WishlistItem>(item);
await _wishListItemRepository.AddAsync(entity);
return _mapper.Map<WishlistItemDto>(entity);
}
Repository:
public async Task<WishlistItem> AddAsync(WishlistItem item)
{
await _context.Set<WishlistItem>().AddAsync(item);
await _context.SaveChangesAsync();
return item;
}
This line here:
var itemAdd = _mapper.Map<WishlistItemDto>(wishListItemDto);
your "wishListItemDto" is passed in as a 'WishListItemCreationDto' which contains only a ProductDetailsId. Automapper will have no way of knowing how to convert that into a ProductDetailsDtoWithPrimaryImage.
Typically for something like this where you pass an reference ID you would compose your entity by either populating a FK or loading the referenced entity. Your existing service and repository patterns will complicate your final solution. From what I can see from your example I'd look at creating an AddAsync method that accepts the WishListItemCreationDto:
public async Task<WishlistItemCreationDto> AddAsync(WishlistItemCreationDto item)
{
var entity = _mapper.Map<WishlistItem>(item);
var productDetails = _productDetailsRepository.GetById(item.ProductDetailsId);
entity.ProductDetails = productDetails;
await _wishListItemRepository.AddAsync(entity);
return _mapper.Map<WishlistItemDto>(entity);
}
Without the added abstraction complexity of the Service and Repository the add operation can be a whole lot simpler:
[HttpPost]
public async Task<IActionResult> Add(WishListItemCreationDto wishListItemDto)
{
// or better, use an injected dependency to the Context...
// TODO: add applicable exception handling.
using(var context = new AppDbContext())
{
var item = _mapper.Map<WishlistItem>(wishListItemDto);
var productDetails = context.ProductDetails.Single(x => x.ProductDetailsId == wishListItemDto.ProductDetailsId);
item.ProductDetails = productDetails;
context.SaveChanges();
return CreatedAtAction(nameof(GetId), new { id = itemCreated.Id }, wishListItemDto);
}
}

Update Navigation Property with Entity.CurrentValues.SetValues

I have a Kalem Entity with a collection of DigerKalemMaliyetleri property, which is a collection of MaliyetBirimi objects. DigerKalemMaliyetleri is of JSON type and stored at the same table as a JSON column.
public class Kalem
{
public int Id { get; set; }
[Column(TypeName = "json")]
public ICollection<MaliyetBirimi> DigerKalemMaliyetleri { get; set; }
}
public class MaliyetBirimi
{
public int? DovizCinsi { get; set; }
public decimal? Maliyet { get; set; }
}
When I try to update entity with only DigerKalemMaliyetleri property changed:
DataContext.Entry<Kalem>(first).CurrentValues.SetValues(second);
SQL Update command isn't executed and database record is not updated.
How could I update the entity without explicitly setting DigerKalemMaliyetleri property?
Regards
I had the same problem, you cann't actually use SetValues to update navigation property, you nead instead use DataContext.Update(YourNewObj) and then DataContext.SaveChanges();, or if you want to use SetValues approach, you need:
-Get the exist entry
Kalem existObj = DataContext.Kalems.Find(YourNewObj.Id);
-Loop in navigations of updating entry and the existing one to set the values of updating entry:
foreach(var navObj in DataContext.Entry(YourNewObj).Navigations)
{
foreach(var navExist in DatatContext.Entry(existObj).Navigations)
{
if(navObj.Metadata.Name == navExist.MetaData.Name)
navExist.CurrentValue = navObj.CurrentValue;
}
}
-Update also changes of direct properties:
DataContext.Entry(existObj).CurrentValues.SetValues(YourNewObj);
-Save your Updating:
DataContext.SaveChanges();
You can also check if you need to load your Navigations before going in foreach loop, otherwise you will get an error.
Please if you see beter scenario, correct me.
It's hard to know exactly what you're doing without a complete code sample. Note also that you're trying to set all properties of first from second, including e.g. the Id, which is probably not what you want.
Here's a complete code sample which works for me:
await using (var ctx = new BlogContext())
{
await ctx.Database.EnsureDeletedAsync();
await ctx.Database.EnsureCreatedAsync();
ctx.Kalem.Add(new()
{
DigerKalemMaliyetleri = new List<MaliyetBirimi>()
{
new() { DovizCinsi = 1, Maliyet = 2 }
}
});
await ctx.SaveChangesAsync();
}
await using (var ctx = new BlogContext())
{
var first = ctx.Kalem.Find(1);
var second = new Kalem
{
DigerKalemMaliyetleri = new List<MaliyetBirimi>()
{
new() { DovizCinsi = 3, Maliyet = 4 }
}
};
ctx.Entry(first).Property(k => k.DigerKalemMaliyetleri).CurrentValue = second.DigerKalemMaliyetleri;
await ctx.SaveChangesAsync();
}
public class BlogContext : DbContext
{
public DbSet<Kalem> Kalem { get; set; }
static ILoggerFactory ContextLoggerFactory
=> LoggerFactory.Create(b => b.AddConsole().AddFilter("", LogLevel.Information));
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseNpgsql(#"Host=localhost;Username=test;Password=test")
.EnableSensitiveDataLogging()
.UseLoggerFactory(ContextLoggerFactory);
}
public class Kalem
{
public int Id { get; set; }
[Column(TypeName = "json")]
public ICollection<MaliyetBirimi> DigerKalemMaliyetleri { get; set; }
}
public class MaliyetBirimi
{
public int? DovizCinsi { get; set; }
public decimal? Maliyet { get; set; }
}

Returning ObjectID as a string from ASP.NET Core

How to you get a string representation of the ObjectId returned via ASP.NET Core.
I have the following result of an action in my controller:
return new ObjectResult(new { session, user });
One of the user properties is the UserId that is of the ObjectId type.
However, this gets returned in the response as
"id": {
"timestamp": 1482840000,
"machine": 6645569,
"pid": 19448,
"increment": 5052063,
"creationTime": "2016-12-27T12:00:00Z"
}
I would like the response to simply be 58625d5201c4f202609fc5f3 that is the string representation of the same structure.
Are there any easy way to do this for all returned ObjectIds?
EDIT
Adding some more data
Here are the user class. ObjectId is MongoDB.Bson.ObjectId
public class User
{
public ObjectId Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string PasswordHash { get; set; }
public string PasswordSalt { get; set; }
}
The get method in my controller. Controller is Microsoft.AspNetCore.Mvc.Controller.
[HttpGet("{id}", Name = "GetUser")]
public async Task<IActionResult> Get(ObjectId id)
{
var user = await _repository.GetOne<User>(id);
if (user == null) return NotFound();
return new ObjectResult(user);
}
And this is the method from my repository:
public async Task<T> GetOne<T>(ObjectId id)
{
var collectionname = typeof(T).Name;
var collection = _database.GetCollection<T>(collectionname);
var filter = Builders<T>.Filter.Eq("_id", id);
var result = await collection.Find(filter).ToListAsync();
return result.FirstOrDefault();
}
You have to explicitly write a ObjectID to JSON convertor. Please check the link below:
https://stackoverflow.com/a/37966098/887976

Invalid date with BreezeJS and Hottowel

i've a problem whit breeze returned DateTime... i've tried also to update BreezeJs to the latest version but nothing change. I use breezeJs with HotTowel SPA
Controller:
[BreezeController]
public class ContribuentiController : ApiController
{
readonly EFContextProvider<LarksTribContext> _contextProvider =
new EFContextProvider<LarksTribContext>();
[System.Web.Http.HttpGet]
public string Metadata()
{
return _contextProvider.Metadata();
}
// ~/api/todos/Todos
// ~/api/todos/Todos?$filter=IsArchived eq false&$orderby=CreatedAt
[System.Web.Http.HttpGet]
public IQueryable<Contribuente> Contribuenti()
{
if (_contextProvider.Context.Contribuente != null)
{
return _contextProvider.Context.Contribuente.Include("Residenze.Strada");//.Include("Residenze").Include("Residenze.Strada");
}
else
{
return null;
}
}
[System.Web.Http.HttpPost]
public SaveResult SaveChanges(JObject saveBundle)
{
return _contextProvider.SaveChanges(saveBundle);
}
}
Model:
[Table(name: "Contribuenti")]
public class Contribuente
{
[Key]
public int Id { get; set; }
[MaxLength(30,ErrorMessage = "Il cognome non deve superare i 30 caratteri")]
public string Cognome { get; set; }
[MaxLength(35, ErrorMessage = "Il nome non deve superare i 35 caratteri")]
public string Nome { get; set; }
[MaxLength(16, ErrorMessage = "Il Codice fiscale non deve superare i 16 caratteri")]
public string CodiceFiscale { get; set; }
public virtual ICollection<Residenza> Residenze { get; set; }
}
[Table(name: "Residenze")]
public class Residenza
{
[Key, Column(Order = 0)]
public int Id { get; set; }
public int ContribuenteId { get; set; }
[ForeignKey("ContribuenteId")]
public Contribuente Contribuente { get; set; }
public DateTime? DataInizio { get; set; }
public int StradaId { get; set; }
[ForeignKey("StradaId")]
public Strada Strada { get; set; }
public int Civico { get; set; }
public string Interno { get; set; }
public string Lettera { get; set; }
}
[Table(name: "Strade")]
public class Strada
{
[Key]
public int Id { get; set; }
[MaxLength(20,ErrorMessage = "Il toponimo deve contenere al massimo 20 caratteri")]
public string Toponimo { get; set; }
[MaxLength(50, ErrorMessage = "Il nome deve contenere al massimo 50 caratteri")]
public string Nome { get; set; }
}
when i make this query:
var query = breeze.EntityQuery.
from("Contribuenti").expand(["Residenze"], ["Strada"]);
the json response is:
[{"$id":"1","$type":"LarksTribUnico.Models.Contribuente, LarksTribUnico","Id":1,"Cognome":"Manuele","Nome":"Pagliarani","CodiceFiscale":"HSDJSHDKHSD","Residenze":[{"$id":"2","$type":"LarksTribUnico.Models.Residenza, LarksTribUnico","Id":5,"ContribuenteId":1,"Contribuente":{"$ref":"1"},"DataInizio":"2012-12-10T22.00.00.000","StradaId":4,"Strada":{"$id":"3","$type":"LarksTribUnico.Models.Strada, LarksTribUnico","Id":4,"Toponimo":"Via","Nome":"Milano"},"Civico":0}]}]
But in result of query "DataInizio" is always marked as "Invalid date".
Any idea aout the problem?
Thanks
Breeze server side converts SQL Server DateTime to ISO 8601. In my code (breeze v0.72) dates seem to end up in UTC in SQL, and get converted back to local somewhere in breeze.
Check the Breeze docs on dates. http://www.breezejs.com/documentation/date-time
or, as suggested in the breeze docs, you can add moment.js to your project if HotTowel does not. https://github.com/moment/moment
Moment recognizes the JSON you are describing.
A moment() is different than a JavaScript date, but it is easier to manipulate and parse.
This code you the current browser date from moment.
var now = window.moment().toDate();
This code demonstrates how to turn an ISO into a JavaScript Date object through moment.
// ISO 8601 datetime returned in JSON.
// In your code, you would pull it out of your the
// return variable in your dataservice.js
var DataInizio = "2012-12-10T22.00.00.000"
// convert your variable to a moment so you can parse it
var momentdatainizio = window.moment(DataInizio);
// convert the ISO to a javascript Date object so you can use it in js.
var mydate = window.moment(DataInizio).toDate();
Your Stada will end up in the breeze Metadata store which you use to populate your viewModel.
Retrieve the strada from the Metadata store or the database with something like this code in your dataservice.js. I am being a little more verbose than necessary so you can debug.
var getStrada = function (stradaId, callback) {
var query = EntityQuery.from("Strada")
.using(manager);
var pred = new breeze.Predicate("idd", "eq", stradaId);
// create the query
var queryb = query.where(pred);
// check the MetadataStore to see if you already have it
var localsession = queryb.executeLocally();
if (localsession) {
if (localsession.length > {
window.app.vm.strada.strada(data.results);
return localsession;
}
}
// get it from the server
else {
// return the promise to prevent blocking
// then set your viewModel when the query fulfills
// then make your callback if there is one
// handle the fail in your queryFailed function if there is a problem
return manager.executeQuery(queryb)
.then(function (data) {
window.app.vm.strada.strada(data.results);
})
.then(function () {
if ((typeof callback !== 'undefined' && callback !== null)) {
callback();
}
})
.fail(function () {
queryFailed();
});
}
};
Here is a fragment of a ko viewModel in strada.js
app.vm.strada = (function ($, ko, dataservice, router) {
var strada = ko.observable();
...
return {
strada : strada,
...
})($, ko, app.dataservice, app.router);
Here is the custom binding handler for knockout in the ko.bindingHandlers.js. This code is slightly verbose so you can debug the intermediate variables.
window.ko.bindingHandlers.DataInizio = {
// viewModel is a Strada
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = valueAccessor(), allBindings = allBindingsAccessor();
var valueUnwrapped = window.ko.utils.unwrapObservable(value);
var $el = $(element);
if (valueUnwrapped.toString().indexOf('Jan 1') >= 0)
$el.text("Strada not Started");
else {
var date = new Date(valueUnwrapped);
var d = moment(date);
$el.text(d.format('MM/DD/YYYY'));
}
}
};
Here is the html for the binding handler
...
Strada DataInizio:
...
I wrote this code based upon my code using Breeze v0.72 which uses sammy.js as the router. Your mileage may vary with newer versions of breeze and Durandel.

Entity Framework , how to only validate specify property

I have a demo class "User" like the following:
public partial class User {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[StringLength(30)]
[Required]
public string LoginName { get; set; }
[StringLength(120)]
[Required]
[DataType(DataType.Password)]
public string Pwd { get; set; }
[StringLength(50)]
public string Phone { get; set; }
[StringLength(100)]
public string WebSite { get; set; }
...
...
}
As you can see, "LoginName" and "Pwd" are "Required".
Some time , I only want to update user's "WebSite" , So I do like this:
public void UpdateUser(User user , params string[] properties) {
this.rep.DB.Users.Attach(user);
this.rep.DB.Configuration.ValidateOnSaveEnabled = false;
var entry = this.rep.DB.Entry(user);
foreach(var prop in properties) {
var entProp = entry.Property(prop);
//var vas = entProp.GetValidationErrors();
entProp.IsModified = true;
}
this.rep.DB.SaveChanges();
this.rep.DB.Configuration.ValidateOnSaveEnabled = true;
}
Parameter "user" like this:
new User(){
ID = 1,
WebSite = "http://www.stackoverflow.com"
}
Notice , I don't specify "LoginName" and "Pwd"
This function can work fine , but I wouldn't set ValidateOnSaveEnabled to false.
Is there any way only validate "WebSite" when ValidateOnSaveEnabled is true?
Thanks.
As I know validation executed in SaveChanges always validates the whole entity. The trick to get selective validation for property is commented in your code but it is not part of the SaveChanges operation.
I get a solution.
First define PartialValidationManager:
public class PartialValidationManager {
private IDictionary<DbEntityEntry , string[]> dics = new Dictionary<DbEntityEntry , string[]>();
public void Register(DbEntityEntry entry , string[] properties) {
if(dics.ContainsKey(entry)) {
dics[entry] = properties;
} else {
dics.Add(entry , properties);
}
}
public void Remove(DbEntityEntry entry) {
dics.Remove(entry);
}
public bool IsResponsibleFor(DbEntityEntry entry) {
return dics.ContainsKey(entry);
}
public void ValidateEntity(DbEntityValidationResult result) {
var entry = result.Entry;
foreach(var prop in dics[entry]){
var errs = entry.Property(prop).GetValidationErrors();
foreach(var err in errs) {
result.ValidationErrors.Add(err);
}
}
}
}
2, Add this Manager to My DbContext:
public class XmjDB : DbContext {
public Lazy<PartialValidationManager> PartialValidation = new Lazy<PartialValidationManager>();
protected override System.Data.Entity.Validation.DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry , IDictionary<object , object> items) {
if(this.PartialValidation.Value.IsResponsibleFor(entityEntry)) {
var result = new DbEntityValidationResult(entityEntry , new List<DbValidationError>());
this.PartialValidation.Value.ValidateEntity(result);
return result;
} else
return base.ValidateEntity(entityEntry , items);
}
...
...
Update Method :
public void UpateSpecifyProperties(T t, params string[] properties) {
this.DB.Set<T>().Attach(t);
var entry = this.DB.Entry<T>(t);
this.DB.PartialValidation.Value.Register(entry , properties);
foreach(var prop in properties) {
entry.Property(prop).IsModified = true;
}
this.DB.SaveChanges();
this.DB.PartialValidation.Value.Remove(entry);
}
Ok, it work fine.