MongoDB id remains null after InsertOneAsync - mongodb

I have a base class Entity that has a string Id member and a derived class A.
But when creating a new instance of the derived class and using InsertOneAsync to add it to my collection, the document is added to the database with null as the Id value.
Using an ObjectId as the Id does seem to work, but I'm trying to prevent MongoDB dependency in my models.
I also experimented with the following code, but the results are the same:
BsonClassMap.RegisterClassMap<Entity>(cm =>
{
cm.MapIdField(x => x.Id).SetSerializer(new StringSerializer(BsonType.ObjectId));
});

I had the same issue and finally got it to work (with the 2.0 driver) with these attributes:
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
[BsonIgnoreIfDefault]
Or the equivalent BsonClassMap fluent interface:
BsonClassMap.RegisterClassMap<Entity>(cm =>
{
cm.MapIdField(x => x.Id)
.SetSerializer(new StringSerializer(BsonType.ObjectId))
.SetIgnoreIfDefault(true);
});
I tried to get the same working with .ReplaceOneAsync with Upsert on but that always leaves the id still null

Are you trying not to use ObjectID in your model. The ID doesn't have to be an objectID. You can decorate a string field as ID.
I have used string property with [BsonId] attribute without any issues.

Related

Entity Framework navigation with only foreign key

Following the guide lines from Domain Driven Design, I try to avoid having one aggregate referencing a different aggregate. Instead, an aggregate should reference another aggregate using the other aggregate's id, for example:
public class Addiction
{
private Addiction(){} //Needed for EF to populate non-simple types
//DrugType belongs to the aggregate,
//inflate when retrieving the Addiction from the db
//EF does not need DrugId for navigation
Drug Drug{get;set;}
//The supplier is not part of the aggregate,
//aggregates only reference eachother using Ids
int SupplierId{get;set;}
//Other properties
}
public class AddictionConfiguration : IEntityTypeConfiguration<Addiction>
{
builder.HasOne(addiction => addiction.Drug); //Works
builder.HasOne("SupplierId") //Does not work.
}
In this (not very realistic) example, Drug is part of the Addiction's aggregate. When loading this entity from the database using EF, it will also inflate the Drug property without me having to specify the DrugId as the foreign key.
However, now I need to get a list of all Addictions and their suppliers by mapping the relevant properties to a Dto. I try to achieve this by using AutoMapper's ProjectTo functionality, e.g.
_mapper.ProjectTo<AddictionDto>(_dbContext.Addictions.Where(x => x.Id > 1));
where AddictionDto is defined as
public class AddictionDto
{
DrugDto Drug {get;set;}
SupplierDto Supplier {get;set;}
//other properties
}
And
public class SupplierDto
{
public int Id {get;set;}
public string Name {get;set;}
}
Automapper correctly loads the Addiction and also the Drug, but I cannot get it to load the Supplier. I've tried all the options of the IEntityTypeConfiguration to tell EF that there is a navigation property, but I cannot get it to work. Does anyone know if is even possible to do what I described above?

TypeOrm findOne throws 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'

Hi I'm using NestJs with TypeOrm and currently connected to a MongoDB (but I want to be independent because most customers use MSSQL and Postgres databases).
Basically I want to store a key/value pair to the database. Both are of type String. This is the mapping entity holding the pair
#Entity()
export class Mapping extends BaseEntity {
#PrimaryColumn()
key: string;
#Column()
value: string;
}
The repository is currently empty
#EntityRepository(Mapping)
export class MappingsRepository extends Repository<Mapping> {}
In my service file I try to find a value by its key
public async getValueByKey(key: string): Promise<string> {
const mapping: Mapping = await this.mappingsRepository.findOne(key);
if (!mapping) {
throw new NotFoundException(`Key ${key} does not exist`);
}
return mapping.value;
}
Unfortunately the findOne function always throws this error when passing in a key
Argument passed in must be a single String of 12 bytes or a string of
24 hex characters
How can I fix this so that I can pass in any keys of type String? The parameter key is defined, I tried it with dummy values like f or ffsdagsdgfdg
Can you try
await this.mappingsRepository.findOne({key});
My guess it that typeorm doesn't understand primary key other than id
findOne for mongo means it will search document by property _id and not your key
because, mongo, by default, always add this _id as unique validator for each document
so, you should provide a query to that method like it is defined in itssajan answer
but i think your use case of TypeORM is not the best, because it is made to work with SQL dbs, and not NoSQL dbs

GORM - get raw DB value for domain class properties

I'm using GORM for MongoDB in my Grails 3 web-app to manage read/writes from DB.
I have the following 2 domain classes:
class Company {
String id
}
class Team {
String id
Company company
}
For teams, their company is saved on DB as String, and with GORM I can simply use team.company to get an instance of Company domain class.
However, I need to override the getter for company, and I need the raw value for company id (as stored on DB), without GORM getting in the way and performing its magic.
Is there a way to get the raw String value?
Any help is welcome! Thanks in advance
Update (May 27)
Investigating #TaiwaneseDavidCheng suggestion, I updated my code to
class Company {
String id
}
class Team {
String id
Company company
String companyId
static mapping = {
company attr: "company" // optional
companyId attr: "company", insertable: false, updateable: false
}
}
Please note that I'm using GORM for MongoDB, which (citing the manual) tries to be as compatible as possible with GORM for Hibernate, but requires a slightly different implementation.
However I found out (by trial&error) that GORM for MongoDB doesn't support a similar solution, as it seems only one property at a time can be mapped to a MongoDB document property.
In particular the last property in alphabetical order wins, e.g. companyId in my example.
I figured out a way to make the whole thing work, I'm posting my own answer below.
given a non-insertable non-updateable column "companyId" in domain class
class Company {
String id
}
class Team {
String id
Company company
Long companyId
static mapping = {
company column:"companyId"
companyId column:"companyId",insertable: false,updateable: false
}
}
(Follows the edit to my question above)
I defined a custom mapping, and made use of Grails transients by also defining custom getter and setter for team's company.
class Company {
String id
}
class Team {
String id
Company company
String companyId
static mapping = {
companyId attr: "company" // match against MongoDB property
}
static transients = [ 'company' ] // non-persistent property
Company getCompany() {
return Company.get(companyId)
}
void setCompany(Company company) {
companyId = company.id
}
}

Foreign Key Object Missing in LINQ GroupBy?

I am using GroupBy in my LINQ queries. My query is working fine, except my foreign key objects are missing. Then, I tried to add Include in my query. Following is my code:
public ActionResult GetEmployees()
{
var Emloyees = db.Employees.AsQueryable();
Emloyees.GroupBy(e=> new {e.JobTitleId, e.GenderId})
.Select(tr => new MyObject
SalaryTotal = tr.Sum(r=>r.Salary)
}).Include(tr=>tr.JobTitle).Include(tr=>tr.Gender).ToList();
}
I am getting this exception:
The result type of the query is neither an EntityType nor a CollectionType with an entity element type. An Include path can only be specified for a query with one of these result types.
I tried to add it before GroupBy and directly in db.Employees.AsQueryable(), but nothing worked. What am I doing wrong?
The problem is that you are doing a projection with the .Select(...), after which your includes cannot be resolved. The result of that query will be a list MyObject, which does not work for includes that are actually on Employee.
So Try it like this:
Emloyees
.GroupBy(e=> new {e.JobTitleId, e.GenderId})
.Select(tr => new MyObject {
SalaryTotal = tr.Sum(r=>r.Salary),
JobTitle = tr.FirstOrDefault().JobTitle,
Gender = tr.FirstOrDefault().Gender
}).ToList();
You will have to extend MyObject with 2 additional properties, but the result of your query will be what you want (I assume).

Entity Framework TPH - Additional WHERE clause only for one subtype

Suppose I have a class Parent, with two subclasses, AChild and BChild. I have these mapped to a single table using Entity Framework 5.0.0 on .NET 4.5, using TPH.
public abstract class Parent {
public string Type { get; set; } // Column with this name in DB is discriminator.
public string Status { get; set; }
}
public class AChild : Parent {
// Other stuff.
}
public class BChild : Parent {
// Other stuff.
}
The code to configure the mapping:
class ParentConfiguration : EntityTypeConfiguration<Parent> {
Map((EntityMappingConfiguration<AChild> mapping) => mapping
.Requires("Type")
.HasValue("A"));
Map((EntityMappingConfiguration<BChild> mapping) => mapping
.Requires("Type")
.HasValue("B"));
}
I have a need to run a query that returns both AChild and BChild objects. However, it needs to filter ONLY the AChild rows by a second column, which in this example I will call Status.
Ideally I would want to do the following:
public IList<Parent> RunQuery() {
IQueryable<Parent> query =
this.context.Set<Parent>()
.Where((Parent parent) => !parent.Type.Equals("A") || parent.Status.Equals("Foo"))
.OrderBy((Parent parent) => parent.Number);
return query.ToList();
}
This doesn't work. It insisted on looking for a "Type1" column instead of just letting both the discriminator and a "Type" property be mapped to the same "Type" column.
I know of the "OfType" extension method that can be used to completely filter down to one type, but that's too broad a brush in this case.
I could possibly run multiple queries and combine the results, but the actual system I'm building is doing paging, so if I need to pull back 10 rows, it gets messy (and inefficient) to query since I'll either end up pulling back too many rows, or not pull back enough and have to run extra queries.
Does anyone have any other thoughts?
There are few problems. First of all you cannot have discriminator mapped as a property. That is the reason why it is looking for Type1 column - your Type property results in second column because the first one is already mapped to .NET types of your classes. The only way to filter derived types is through OfType.
The query you want to build will be probably quite complex because you need to query for all Bs and concatenate them with result of query for filtered As. It will most probably not allow you to concatenate instances of Bs with As so you will have to convert them back to parent type.