Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Automapper to map object to realm object with Xamarin and c#

I am creating an Xamarin.iOS app and a Realm database.I would like to keep my POCO objects separate from my RealmObject so what I did was use a repository pattern and within the repository I tried to use AutoMapper to map the POCO to the RealmObject

e.g. (subset)

public class PlaceRepository : IPlaceRepository
{
    private Realm _realm;

    public PlaceRepository(RealmConfiguration config)
    {
        _realm = Realm.GetInstance(config);
    }

    public void Add(Place place)
    {
        using (var trans = _realm.BeginWrite())
        {
            var placeRealm = _realm.CreateObject<PlaceRealm>();
            placeRealm = Mapper.Map<Place, PlaceRealm>(place);

            trans.Commit();
        }
    }

So, if I debug my code everything maps OK and placeRealm is populated OK but when I commit nothing gets saved to the Realm db. The following is my RealmObject

public class PlaceRealm : RealmObject
{
    [ObjectId]
    public string Guid { get; set; }
    public string Title { get; set; }
    public string Notes { get; set; }
 }

and this is my POCO Place

public class Place
{
    public string Guid { get; set; }
    public string Title { get; set; }
    public string Notes { get; set; }
 }

And AutoMapper is initialized like so:

 Mapper.Initialize(cfg =>
 {
      cfg.CreateMap<Place, PlaceRealm>();
      cfg.CreateMap<PlaceRealm, Place>();
  });

All standard stuff. Has anyone else managed to get something similar working?

like image 684
FinniusFrog Avatar asked Oct 31 '22 00:10

FinniusFrog


1 Answers

Your poco 'Place' is called 'PlaceRealm'. I suspect that is a typo. (made edit)

I suspect that Automapper is instantiating a new object overwriting your original 'placeRealm' object. Perhaps you could try

Mapper.Map(place, placeRealm);

in place of your current mapping. which should just copy the values to your already instatiated and tracked object. (no need to store the return value).

You might also want to make explicit which properties (3) you are mapping as currently Automapper will map all including those in the base class.

On a side note, you may run into performance issues with Automapper. I found it to be the performance bottleneck in some apps. ExpressMapper is a nice alternative.

like image 154
Damian Green Avatar answered Dec 10 '22 12:12

Damian Green