user3624511
user3624511

Reputation: 27

Unable to cast object of type 'System.Data.Entity.DynamicProxies.Organisation to type 'Site.Models.Person'

 try
        {
            person = (Person) database.People.SingleOrDefault(e => e.Username == User.Identity.Name);
          //  m_objLog.Debug("Found user :" + User.Identity.Name);
        }
        catch (Exception ex)
        {
            m_objLog.Debug(ex.Message);
            throw new Exception(ex.Message);
        }

And My Person Model is bellow

protected override void Initialize() {
            base.Initialize();
            EmailAddresses = new List<EmailAddress>();
            TelephoneNumbers = new List<TelephoneNumber>();
}
[InverseProperty("Person")]
        public virtual List<EmailAddress> EmailAddresses { get; set; }
    [InverseProperty("Person")]
        public virtual List<TelephoneNumber> TelephoneNumbers { get; set; }

    [Display(Name = "Username")]
    public string Username { get; set; }
[InverseProperty("People")]
        public virtual Organisation Organisation { get; set; }

I am not sure why it is producing error; am I not casting properly in person = (Person) database.People.SingleOrDefault(e => e.Username == User.Identity.Name);

Please advice.

Upvotes: 0

Views: 680

Answers (1)

Mike Nakis
Mike Nakis

Reputation: 61993

A "person" is linked to a specific organization.

An "organization" cannot be linked to a specific person. (It would not make sense.)

In ORM, an "organization" can be seen as having a set of persons who are associated with it, but that relationship is encoded in the "person belongs to organization" relationship. (By means of the [InverseProperty] annotation.)

Therefore, it is wrong to say the following:

[InverseProperty("People")]
public virtual Organisation Organisation { get; set; }

There can be no "inverse property here". It does not make any sense. And it could not possibly work, because it would be a circular relationship definition: it is like telling the ORM to look at the organization of a person in order to figure out the persons of the organization, but then also to look at the persons of an organization in order to figure out the organization of a person.

So, just strip the [InverseProperty("People")] line.

Upvotes: 1

Related Questions