Search code examples
c#asp.net-mvc-5entity-framework-6ef-database-first

Unable to cast location to ILocation


I am getting a rather weird casting error. Here is the code:

public class OrganizationLocation : IOrganizationLocation
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

public interface IOrganizationLocation
{
    string Name { get; }
}

public class Organization : IOrganization
{
    public Guid Id { get; set; }
    public string Alias { get; set; }

    public virtual ICollection<OrganizationLocation> Location { get; set; }

    public ICollection<IOrganizationLocation> Locations
    {
        get
        {
            return (ICollection<IOrganizationLocation>) Location;
        }
    }
}

public interface IOrganization
{
    string Alias { get; }
    ICollection<IOrganizationLocation> Locations { get; }
}

now when I try to run this via a service (backend data layer is EF6), the "Location" variable has all the values, however, the "Locations" variable fails to cast. If I try to do a safe cast, it comes back as null every time.

I'm not understanding why would the cast fail? It has same fields, both are ICollection Type, so why do I get a HashSet?

The reason why I am doing it this way is because for EF6 framework to be able to treat this class as a table it needs to have a concrete type and a public get/set. However, I do not wish to expose that, so I use interface instead and then inject the class when the interface is called. This way I only expose get method and on top of it I only expose interface layers.

Unable to cast object of type 'System.Collections.Generic.HashSet`1[Namespace.OrganizationLocation]' to type 'System.Collections.Generic.ICollection`1[Namespace2.IOrganizationLocation]'.


Solution

  • I was able to resolve this by changing the code to the following:

    public class OrganizationLocation : IOrganizationLocation
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
    }
    
    public interface IOrganizationLocation
    {
        string Name { get; }
    }
    
    public class Organization : IOrganization
    {
        public Guid Id { get; set; }
        public string Alias { get; set; }
    
        public virtual ICollection<OrganizationLocation> Location { get; set; }
    
        public IEnumerable<IOrganizationLocation> Locations => Location
    }
    
    public interface IOrganization
    {
        string Alias { get; }
        IEnumerable<IOrganizationLocation> Locations { get; }
    }