Xamarin Forms, Grouping Realm - xamarin

I am using Xamarin forms (.NET Standard project), Realm & MVVM Light and I need to group a list of objects based on the Initial of the last name so that I can display a jumplist within a listview.
I am having a problem when trying to group a RealmObject. I have a model like so...
public class Participant : RealmObject
{
public string FirstName {get; set;}
public string LastName {get; set;}
public string Email {get; set;}
public string RegistrationCode {get; set;}
//More properties skipped out for brevity
}
Based on this link, I also have a Grouping class like so...
public class Grouping<K, T> : ObservableCollection<T>
{
public K Key { get; private set; }
public Grouping(K key, IEnumerable<T> items)
{
Key = key;
foreach (var item in items)
this.Items.Add(item);
}
}
In my viewmodel, I am able to fetch the Participants (i.e IQueryable<Participant>) like so....
var participants = RealmInstance.All<Participant>();
I would now like to be able to group this by Initials of the last name for which I do the following:
var groupedParticipants = from participant in participants
group participant by participant.LastName.Substring(0, 1) into pGroup
orderby pGroup.Key
select new Grouping<string, Participant>(pGroup.Key, pGroup);
which throws the below exception:
System.TypeInitializationException: The type initializer for 'Realms.RealmCollectionBase' threw an exception. ---> System.ArgumentException: The property type IGrouping cannot be expressed as a Realm schema type
I have looked around but unable to find working examples of grouping Realm sets. Any help would be greatly appreciated.

Realm does not support Linq's GroupBy (or Select-based projections).
A workaround would be to take a Realm-based sorted query to a standard List and then perform your Linq GroupBy.
Example (using James Montemagno's Monkey project):
var realmSort = r.All<Monkey>().OrderBy(m => m.Name).ToList();
var sorted = from monkey in realmSort
orderby monkey.Name
group monkey by monkey.NameSort into monkeyGroup
select new Grouping<string, Monkey>(monkeyGroup.Key, monkeyGroup);

Related

How to persist a model when doing Create / Edit in MVC3 before saving it to the database?

basically I am talking about the thing what we had in ASP.NET, called ViewState.
Here is the example, to keep it simple, I have a model Employee:
public class Employee
{
public string EmployeeId { get; set; }
public string Name { get; set; }
public string Company { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
}
My company created records for employees with their EmployeeId, Name and Company.
The employee needs to enter (update) only his Phone number and Address.
When I present a form in Edit / or Create mode for employee to enter this information, EmployeeID, Name and Company outputted just as text, while Phone and Address are editable fields (Html.EditorFor), which allows to keep values entered in the Model object.
When this form is HTTP posted back, lets say, validation fails, and the form is presented to the user again to correct his input (View(model)).
However the values for EmployeeID, Name and Company are lost, since they were not defined as Html.EditorFor, like Phone and Address, and therefore are not preserved, when the submitted model is being passed again into the View.
How do I preserve (persist) in the Model those properties (that are not editable)?
Thank you.
Simply use Html.HiddenFor and store the values on the page. You could also use the mvc futures project and Html.Serialize it, but then you are mimicking viewstate when it's not necessary.

How do I delete a related object with a 1 to 1 relationship in the Entity Framework?

I'm using EF Model First and in my Employee class I have a Manager property with a 1 to 1 relationship to itself, the Employee class:
public partial class Employee
{
public Employee()
{
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual Employee Manager { get; set; }
}
Now, when I get an existing object from the database and change the manager with:
employee.Manager = otherEmployeeInstance;
Context.Entry(employee).State = System.Data.EntityState.Modified;
Context.SaveChanges();
It works just fine; however, if I want to remove the manager this will not work:
employee.Manager = null;
It looks to me that I first need to "load" the manager (Employee) instance into the context since this makes it work:
var dummyVar = employee.Manager.Id;
employee.Manager = null;
So the question is, what's the best (proper) way to remove a related object?
obviously, when you want to delete an entity of the one-to-one relationship, the EF doesn't allow to delete it without preparing it before. that is, removing any dependent entity information from that entity. Remember, we are using Relational Database system and any breaking relation without any coordination causes to anomaly and failure.
When you want to remove a relation, you can use this at your controller:
employee.Remove(Manager);//Automatically Removes Navigational Properties at both entities
db.SaveChanges();
Instead of this :
employee.Manager = null;

Specified type member is not supported in linq to entities

Hi hope someone can help.
I have an EF4 context with 2 POCO based entities that map on to 2 tables in a legacy SQL2005 database. There are no relationships betwen the tables and no associations between the entity definitions in the context.
public class Venue
{
public Venue(){}
public string LocationCode {get;set;}
public string LocationName {get;set;}
}
public class Booking
{
public Booking(){}
public string LocationCode {get;set;}
public int EventReference {get;set;}
public Venue BookingVenue {get;set;}
public Event BookingEvent {get;set;}
}
public class Event
{
public Event(){}
public int EventReference {get;set;}
public DateTime EventStart {get;set;}
/* plus another 60 or so properties */
}
I can do a LINQ select from each individually but whenever I try and join between Event and Booking I get
The specified type member ‘BookingEvent’ is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
I've tried all the workarounds I can find across the web (there are no enums, calcualted properties, etc) and I'm more than a little frustrated now.
Help ?
Here's the query in question....
List<Booking> bookings = (from b in CalendarDB.Bookings
join e in CalendarDB.Events join b.EventReference on e.EventReference
select b).ToList();
Without the relationships in the model, I don't think EF can figure out what data to use to join on. Even though your Booking class has a BookingEvent property, EF doesn't just 'know' that it needs to join on the Event table based on Booking.EventReference. Because of that, any query which attempts to use those reference properties will fail.

Class diagrams to show relation between classes?

Are class diagrams in visual studio supposed to show relation between classes, for eg. 1 : many.
public class User
{
public string UserId { get; set; }
public List<Role> Roles { get; set; }
}
public class Role {
public int RoleId {get; set;}
public User User {get; set;}
public string UserId {get; set; }
}
Edit:
To clarify.. Class diagram generally isn't supposed to show relations (1:n, m:n etc.) because those relations are for database tables (entities). Classic class diagram is more suited for analysis and design, so it shows associations instead of relations.
Original answer:
Yes you can show 'relations', but you wont see any numbers afaik. It has its own way of showing. Numbers are shown in Entity Framework model for example.
How to show associations:
Move classes into diagram, and then right click on property Roles and pick Show as collection association.
If you want to show more advanced associations here is an addin for Visual studio from CodePlex.

Populate DTO from several queries

I have a DTO with 40+ properties. But in order to populate all properties I need to execute 4 separate queries. My first query is in charged of getting basic information. For each row returned I run 3 more queries based on the id's given from the main query (N+1 problem). I can set use eager loading but then I'm loading thousands of objects that I don't need.
Should I split my DTO and create a separate DTO for each query I run then link then tie them all together into a central DTO by id?
I was envisioning a final DTO like this.
public class FooDto
{
public string Foo { get; set; }
public string Bar { get; set; }
public FirstDto FirstQueryResults { get; set; }
public SecondDto SecondQueryResults { get; set; }
public ThirdDto ThirdQueryResults { get; set; }
}
Is there a better way of solving this? I'm using Oracle and NHibernate doesn't support multi criterias. Note that I am joining most of my data. The problem comes when I need to query data with a complete new set of criteria.
How about creating a VIEW that joins the data to give the 40 properties all in one go, and basing your DTO on that - whatever a DTO may be ;-)

Resources