How do I get the entity type of a foreign key field?

Posts   
 
    
Posts: 9
Joined: 06-Sep-2012
# Posted on: 06-Sep-2012 11:01:07   

Hi,

my problem is following:

I have two entities: company and contact. A company has several contacts. Owner, Manager1, Manager2, and so on. The relation is 1:1.

Somewhere in my code I have a contact, without any information to which field it belongs. All I know is that it belongs to a company.

Now I need to determine the contact type.

My idea was to iterate all entity fields which are a contact and check if any of those contain my contact ID. With the field name I'm able to decide what type of contact it is.

This was my first try:

public string DetermineContactType(ContactEntity entity) {
    var contactFields = Fields.OfType<IEntityFieldCore>().Where(x => x.DataType == typeof (ContactEntity));
    var matchingField = contactFields.FirstOrDefault(x => x.CurrentValue == (object)entity.Id);
    
    if(matchingField == null)
        return null;

    return matchingField.Name;
}

However, this doesn't work as DataType isn't of type Entity, rather it is an int.

Is there any other way to get the entity type of a field?

Thanks in advance!

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 06-Sep-2012 19:18:32   

I'd say the design needs to be re-assesed. IMHO the relation should be Company 1:m Contact And the Company doesn't point to a Contact. Each COntact should have a FK pointing to the Company. And then youshould have the Type of the Contact stored insde the Contact.

A field saying whether it's a manager or the owner ... etc.

Posts: 9
Joined: 06-Sep-2012
# Posted on: 06-Sep-2012 21:02:38   

You are right, that is actually the correct approach for my problem. I had the same thoughts a little bit later.

However, it would take me much more time to redesign all the entities, update existing data and fix code dependencies.

I'm still interested to know if it is possible to get the entity type of a foreign key field.

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 07-Sep-2012 08:12:52   

JonathanEgerton wrote:

I'm still interested to know if it is possible to get the entity type of a foreign key field.

You should look into navigators instead of a FK field, as a relation (thus navigator) could be composed of more than one FK field. This is an idea (no tested):

public string DetermineContactType(ContactEntity contact) 
{
    var company = contact.Company;

    var relatedData = ((IEntityCore)company).GetRelatedData();
    var navigator =  relatedData.FirstOrDefault(kv => kv.Value is ContactEntity && ((Contactentity)kv.Value) == contact);

    var navigatorName = string.Empty;
    if (navigator.Value != null)
    {
        navigatorName = navigator.Key;
    }

    return navigatorName;
}
David Elizondo | LLBLGen Support Team
Posts: 9
Joined: 06-Sep-2012
# Posted on: 07-Sep-2012 09:11:32   

Thank you! Works perfectly!