Tuesday, August 7, 2012

How to add custom unbound property to LINQ2SQL , EF

We encountered this error because we did not map entity property OrganizationName to certain table column in the database. You can check the table mapping by right click the entity User and select “Table Mapping”.
However, I don’t think we can solve the problem by only adding a custom property in the designer. Even we add the Organization table in the Mapping Details and map the OrganizationName property to Organization.Name column, EF still wants us to map the PK of the Organization table to one property in the User entity. But the FK property of User entity is not Entity Key, so the entire mapping still fails. Hope I made it clear to understand.
To workaround, I would recommend you to write some hard code to add a custom property into the User class. Since all the entity classes are partial classes, we can create a new partial User class and add the custom property outside the EDM designer:
==========================================================================
public partial class User
{
public string OrganizationName
{
get
{
if (this.Organization != null)
return this.Organization.Name;
else
return string.Empty;
}
set
{
if (this.Organization != null)
this.Organization.Name = value;
}
}
}
==========================================================================
BTW, I should mention the lazy loading feature of EF4 which is not available in EFv1. That mentions the related entities will not be loaded until we try to access them. If this case, if we turn off the lazy loading feature by (context.ContextOptions.LazyLoadingEnabled = false), we need to add such a filter in the getter/setter of property OrganizationName:
==========================================================================
if (!this.OrganizationReference.IsLoaded)
{
this.OrganizationReference.Load();
}
==========================================================================

No comments:

Post a Comment