I'm using MongoDB and official C# driver 0.9
I'm just checking how embedding simple documents works.
There are 2 easy classes:
public class User
{
public ObjectId _id { get; set; }
public string Name { get; set; }
public IEnumerable<Address> Addresses { get;set; }
}
public class Address
{
public ObjectId _id { get; set; }
public string Street { get; set; }
public string House { get; set; }
}
I create a new user:
var user = new User
{
Name = "Sam",
Addresses = (new Address[] { new Address { House = "BIGHOUSE", Street = "BIGSTREET" } })
};
collection.Insert(user.ToBsonDocument());
The user is successfully saved, so is his address.
After typing
db.users.find()
in MongoDB shell, I got the following result:
{ "_id" : ObjectId("4e572f2a3a6c471d3868b81d"), "Name" : "Sam", "Addresses" : [
{
"_id" : ObjectId("000000000000000000000000"),
"Street" : "BIGSTREET",
"House" : "BIGHOUSE"
}
] }
Why is address' object id 0?
Doing queries with the address works though:
collection.FindOne(Query.EQ("Addresses.Street", streetName));
It returns the user "Sam".
It's not so much a bug as a case of unmet expectations. Only the top level _id is automatically assigned a value. Any embedded _ids should be assigned values by the client code (use ObjectId.GenerateNewId). It's also possible that you don't even need an ObjectId in the Address class (what is the purpose of it?).
Use BsonId attribute:
public class Address
{
[BsonId]
public string _id { get; set; }
public string Street { get; set; }
public string House { get; set; }
}
Identifying the Id field or property
To identify which field or property of
a class is the Id you can write:
public class MyClass {
[BsonId]
public string SomeProperty { get; set; }
}
Driver Tutorial
Edit
It's actually not working. I will check later why.
If you need get it work use following:
[Test]
public void Test()
{
var collection = Read.Database.GetCollection("test");
var user = new User
{
Name = "Sam",
Addresses = (new Address[] { new Address { House = "BIGHOUSE", Street = "BIGSTREET", _id = ObjectId.GenerateNewId().ToString() } })
};
collection.Insert(user.ToBsonDocument());
}
Get the collection as User type:
var collection = db.GetCollection<User>("users");
Initialize the field _id as follows:
var user = new User
{
_id = ObjectId.Empty,
Name = "Sam",
Addresses = (new Address[] { new Address { House = "BIGHOUSE", Street = "BIGSTREET" } })
};
Then you insert the object:
collection.InsertOne(user);
The _id field will automatically be generated.
In this link you will find alternative ways to have customized auto-generated ID(s).
Related
Model structure:
//Main doc model
Public class MainDocumentModel
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Name{ get; set; }
public List<SubDocuementModel> SubDocsList { get; set; }
}
//sub doc model
Public class SubDocumentModel
{
public string Id { get; set; }
[BsonIgnoreIfNull]
public string MainDocId { get; set; }
public string Name{ get; set; }
[BsonIgnoreIfNull]
public List<SubDocuementModel> SubDocsList { get; set; }
.
.
.
}
In DB when I insert MainDocuement, its structure looks like:
{
"_id" : ObjectId("54b9d732bb63bc10ec9bad6f"),
"Name" : "Name-1",
"SubDocsList : [{
"Id" : "54b9e76dbb63bc1890e8761b",
"Name" : "Sub-Name-1"
},....]
}
Now I want to retrieve subdocuments where main doc Id == 54b9d732bb63bc10ec9bad6f:
private void getSubDoc(SubDocumentModel oModel)
{
_MainDoc = _db.GetCollection<MainDocumentModel>("MainDoc");
_query = Query<MainDocumentModel>.Where(e => e.Id == oModel.MainDocId);
//Here I get the exception
//Exception: An error occurred while deserializing the SubDocsList property
of class Data.MainDocumentModel: Element 'Id' does not match any field or
property of class Data.SubDocumentModel.
private MainDocumentModel _mainDocModel = _MainDoc.FindOneAs<MainDocumentModel>(_query);
oModel.SubDocsList =
_mainDocModel .SubDocsList .FindAll(
x => x.Name.ToLower().Contains("NameFilter"));
//Pagination
oModel.SubDocsList =
oModel.SubDocsList .Take(oModel.ItemsPerPage)
.Skip(oModel.ItemsPerPage*(oModel.PageNo - 1))
.ToList();
}
Why I am getting above deserializing exception. What I am doing wrong?
Here I am applying the pagination logic to the retrieved c# list. How I can apply pagination itself in mongo query?
It's very easy to apply pagination for main doc as:
mainDocCursor = MainDoc .Find(_query).SetSortOrder(SortBy.Ascending("Name")).SetLimit(oModel.ItemsPerPage).SetSkip(oModel.ItemsPerPage * (oModel.PageNo - 1));
How can I achieve the same pagination for subdocuments?
I solved the exception of deserializing, with following small changes:
In SubDocumentModel:
Public class SubDocumentModel
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
.
.
.
}
And when I insert the subdocument, I am saving the Id as object id not as a string (previously I was saving it as a string which was causing the problem):
public void addSubDocument(SubDocumentModeloModel)
{
_MainDoc = _db.GetCollection<MainDocumentModel>("MainDoc");
BsonDocument subDocument = new BsonDocument
{
{"_id", ObjectId.GenerateNewId()},//Previously it was {"Id", ObjectId.GenerateNewId().ToString()}
{"Type", oModel.Name}
};
_query = Query<MainDocumentModel>.Where(e => e.Id == oModel.MainDocId);
_updateBuilder = Update.Push("SubDocsList", subDocument);
_MainDoc.Update(_query, _updateBuilder);
}
However I've still not found a way for pagination of subdocument in mongodb-c#
I'm looking to be able to reuse some of the transform expressions from indexes so I can perform identical transformations in my service layer when the document is already available.
For example, whether it's by a query or by transforming an existing document at the service layer, I want to produce a ViewModel object with this shape:
public class ClientBrief
{
public int Id { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
// ellided
}
From this document model:
public class Client
{
public int Id { get; private set; }
public CompleteName Name { get; private set; }
public Dictionary<EmailAddressKey, EmailAddress> Emails { get; private set; }
// ellided
}
public class CompleteName
{
public string Title { get; set; }
public string GivenName { get; set; }
public string MiddleName { get; set; }
public string Initials { get; set; }
public string Surname { get; set; }
public string Suffix { get; set; }
public string FullName { get; set; }
}
public enum EmailAddressKey
{
EmailAddress1,
EmailAddress2,
EmailAddress3
}
public class EmailAddress
{
public string Address { get; set; }
public string Name { get; set; }
public string RoutingType { get; set; }
}
I have an expression to transform a full Client document to a ClientBrief view model:
static Expression<Func<IClientSideDatabase, Client, ClientBrief>> ClientBrief = (db, client) =>
new ClientBrief
{
Id = client.Id,
FullName = client.Name.FullName,
Email = client.Emails.Select(x => x.Value.Address).FirstOrDefault()
// ellided
};
This expression is then manipulated using an expression visitor so it can be used as the TransformResults property of an index (Client_Search) which, once it has been generated at application startup, has the following definition in Raven Studio:
Map:
docs.Clients.Select(client => new {
Query = new object[] {
client.Name.FullName,
client.Emails.SelectMany(x => x.Value.Address.Split(new char[] {
'#'
})) // ellided
}
})
(The Query field is analysed.)
Transform:
results.Select(result => new {
result = result,
client = Database.Load(result.Id.ToString())
}).Select(this0 => new {
Id = this0.client.__document_id,
FullName = this0.client.Name.FullName,
Email = DynamicEnumerable.FirstOrDefault(this0.client.Emails.Select(x => x.Value.Address))
})
However, the transformation expression used to create the index can then also be used in the service layer locally when I already have a Client document:
var brief = ClientBrief.Compile().Invoke(null, client);
It allows me to only have to have one piece of code that understands the mapping from Client to ClientBrief, whether that code is running in the database or the client app. It all seems to work ok, except the query results all have an Id of 0.
How can I get the Id property (integer) properly populated in the query?
I've read a number of similar questions here but none of the suggested answers seem to work. (Changing the Ids to strings from integers is not an option.)
I have a hard time following your sample fully, Really the best way to dig in to this would be with a failing self-contained unit test.
Nonetheless, let's see if I can pull out the important bits.
In the transform, you have two areas where you are working with the id:
...
client = Database.Load(result.Id.ToString())
...
Id = this0.client.__document_id,
...
The result.Id in the first line and the Id = in the second line are expected to be integers.
The Database.Load() expects a string document key and that is also what you see in __document_id.
The confusion comes from Raven's documentation, code, and examples all use the terms id and key interchangeably, but this is only true when you use string identifiers. When you use non-string identifiers, such as ints or guids, the id may be 123, but the document key is still clients/123.
So try changing your transform so it translates:
...
client = Database.Load("clients/" + result.Id)
...
Id = int.Parse(this0.client.__document_id.Split("/")[1]),
...
... or whatever the c# equivalent linq form would be.
I have the following sample objects..
public class ComplexObject
{
public string Name { get; set; }
public SimpleObject Child1 { get; set; }
public SimpleObject Child2 { get; set; }
}
public class SimpleObject : IEquatable< SimpleObject >
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public int? Age { get; set; }
}
with the following AutoMapper configuration
Mapper.CreateMap<SimpleObject, SimpleObject>()
.ForAllMembers(expression=>expression.Condition(r=>!r.IsSourceValueNull));
Mapper.CreateMap<ComplexObject, ComplexObject>()
.ForAllMembers(expression=>expression.Condition(resolutionContext=>!resolutionContext.IsSourceValueNull));
and the following NUnit test...
[SetUp] public void Should_run_before_each_test()
{
child1 = new SimpleObject { FirstName = "Tom", LastName = "Smith", Age = 34, Gender = "Male" };
child2 = new SimpleObject { FirstName = "Andy", LastName = "Smith-bob", Age = 21, Gender = "Male" };
}
[ Test ]
public void Should_ignore_null_properties_in_nested_objects()
{
var source = new ComplexObject()
{
Name = "blue",
Child1 = new SimpleObject{FirstName = "dot", LastName = "net"}
};
var destination = new ComplexObject()
{
Name = "Andy",
Child1 = child1,
Child2 = child2
};
destination = Mapper.Map(source, destination);
destination.Name.Should(Be.EqualTo(source.Name));
destination.Child1.FirstName.Should(Be.EqualTo("dot"));
destination.Child1.LastName.Should(Be.EqualTo("net") );
destination.Child1.Age.Should(Be.EqualTo(child1.Age) );
destination.Child1.Gender.Should(Be.EqualTo(child1.Gender) );
}
The above test fails when asserting the age as AutoMapper is pushing null through to the destination object.
Am I expecting too much from AutoMapper, or have I missed some vital map configuration step.
The ultimate goal is to have a very complex domain object bound to incoming form data via an MVC action. AutoMapper will then be used to merge only non-null properties (at all depths of the object graph) into the real instance being maintained throughout a multi step form.
Just in case anyone needs to know... I have also tried the following mapping configuration without any luck :(
Mapper.CreateMap<ComplexObject, ComplexObject>()
.ForMember(x=>x.Child1, l=>l.ResolveUsing(x=>x.Child1 == null?null:Mapper.Map<SimpleObject,SimpleObject>(x.Child1)))
.ForMember(x=>x.Child2, l=>l.ResolveUsing(x=>x.Child2 == null?null:Mapper.Map<SimpleObject,SimpleObject>(x.Child2)))
.ForAllMembers(expression=>expression.Condition(resolutionContext=>!resolutionContext.IsSourceValueNull));
Why do you expect the value on the destination object is not null if the source value is null? The default value for int? is null, and therefore, when you call
destination.Child1.Age.Should(Be.EqualTo(child1.Age));
The .Should is what's failing. This should be expected behavior.
Try something like Assert.Null(detination.Child1.Age), and it should pass. AutoMapper is not 'pushing' the value through, there is no source value and therefore, Age is just going to have it's default value.
we have a json serializer and deserializer downloaded, it reads the profile object find, but its not putting in the Client item in the list. Here is the json
{"Profile": [{
"Name":"Joe",
"Last :"Doe",
"Client":
{
"ClientId":"1",
"Product":"Apple",
"Message":"Peter likes apples"
},
"Date":"2012-02-14"
}]}
So in my profile class i have
public class Profile
{
public string Name {get; set;}
public string Last {get; set;}
public List<Client> Client {get; set;}
public DateTime dDate {get; set;}
public Profile()
{
}
public Profile BuildEntity()
{
Profile profile = new Profile();
profile.Name = this.Name;
profile.Last = this.LastName;
profile.Client = this.client;
profile.dDate = this.dDate;
return dDate;
}
}
Now, when I debug all the items have values except for the list. Does anyone know what it might be?
NOTE: This is being posted to our Profile.asmx web service
Regards
You declared Client as:
public List<Client> Client {get; set;}
But your data looks like this:
"Client":
{
"ClientId":"1",
"Product":"Apple",
"Message":"Peter likes apples"
}
I think the data expected is more like:
"Client":
[{
"ClientId":"1",
"Product":"Apple",
"Message":"Peter likes apples"
}]
The de-serialization is probably expecting an array of objects, rather than just an object.
Maybe client should be an array, not an object because un you model it is a List. try with this:
"Client":
[{
"ClientId":"1",
"Product":"Apple",
"Message":"Peter likes apples"
}],
In the future I would recommend using LinqPad to test with and then implement. Below is the working code sample.
string JASON = #"
{""Profile"": [{
""Name"":""Joe"",
""Last"":""Doe"",
""Client"":
{
""ClientId"":""1"",
""Product"":""Apple"",
""Message"":""Peter likes apples""
},
""Date"":""2012-02-14""
}]}
";
void Main()
{
var jason = JsonConvert.SerializeObject(Container.Instance());
JASON.Dump();
jason.Dump();
JsonConvert.DeserializeObject(JASON).Dump();
}
// Define other methods and classes here
class Container
{
public Container()
{
Profile = new List { };
}
public List Profile { get; set; }
public static Container Instance()
{
var c = new Container();
c.Profile.Add(
new Profile {
Name = "Joe",
Last = "Doe",
Date = "2012-02-14",
Client = new Client{ ClientId = 1, Product = "Apple", Message = "Peter likes apples" }
});
return c;
}
}
class Client
{
public int ClientId { get; set; }
public string Product { get; set; }
public string Message { get; set; }
}
class Profile
{
public string Name {get; set;}
public string Last {get; set;}
public Client Client {get; set;}
public string Date {get; set;}
public Profile()
{ }
}
I have a company that contains an address object. The SQL return is flat, and I'm tring to get Query<> to load all the objects.
cnn.Query<Company,Mailing,Physical,Company>("Sproc",
(org,mail,phy) =>
{
org.Mailing = mail;
org.Physical = phy;
return org;
},
new { ListOfPartyId = stringList }, null, true, commandTimeout: null,
commandType: CommandType.StoredProcedure, splitOn: "MailingId,PhyscialId").ToList();
I'm not sure if i have the SplitOn correct either. I'm getting the message:
When using the multi-mapping APIs ensure you set the splitOn param if
you have keys other than Id Parameter name: splitOn
Suggestions would be great.
The examples in the Test.cs are not what the code asks for as parameters for the queries. These need to be updated
for me this works perfect ... perhaps a typo?
I see PhyscialId which definitely looks like one.
class Company
{
public int Id { get; set; }
public string Name { get; set; }
public Mailing Mailing { get; set; }
public Physical Physical { get; set; }
}
class Mailing
{
public int MailingId { get; set; }
public string Name { get; set; }
}
class Physical
{
public int PhysicalId { get; set; }
public string Name { get; set; }
}
public void TestSOQuestion()
{
string sql = #"select 1 as Id, 'hi' as Name, 1 as MailingId,
'bob' as Name, 2 as PhysicalId, 'bill' as Name";
var item = connection.Query<Company, Mailing, Physical, Company>(sql,
(org, mail, phy) =>
{
org.Mailing = mail;
org.Physical = phy;
return org;
},
splitOn: "MailingId,PhysicalId").First();
item.Mailing.Name.IsEqualTo("bob");
item.Physical.Name.IsEqualTo("bill");
}