Create relationship w/o PK and FK

Posts   
 
    
Derek
User
Posts: 2
Joined: 06-Jul-2007
# Posted on: 06-Jul-2007 00:34:21   

Currently I am working on some legacy DB tables that do have a relationship but do not have a foreign key relationship defined between them. Is there a way to programatically define a relationship between two tables?

For example, I have the tables dbo.ReportHistory and dbo.Consumer. Dbo.ReportHistory has a field called ConsumerId which maps to the dbo.Consumer's Id field.

Normally, I would use the code to define the relationship:

RelationPredicateBucket bucket = new RelationPredicateBucket(); bucket.Relations.Add(ReportHistoryEntity.Relations.ReportHistoryEntityUsingConsumerId);

but b/c there is no foreign key relationship defined, this relation does not exist. Is it possible to create a relationship outside of defining it as a foreign key relation and doing a code regen?

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 06-Jul-2007 10:30:03   

You can use the designer to define a relation between 2 tables, this relation can be defined between any entity/table's PK and another field with the same type in another entity/table.

Please refer to the manual's section: "Using the designer -> Adding custom relations"

Derek
User
Posts: 2
Joined: 06-Jul-2007
# Posted on: 06-Jul-2007 18:33:00   

First, thanks for the response.

But yes I've read that section. I was actually trying not to touch the designer or re-generate the code. I was hoping there was a method using code to define a relationship between two tables.

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 07-Jul-2007 04:39:53   

Hi Derek,

Derek wrote:

Normally, I would use the code to define the relationship:

RelationPredicateBucket bucket = new RelationPredicateBucket(); bucket.Relations.Add(ReportHistoryEntity.Relations.ReportHistoryEntityUsingConsumerId);

but b/c there is no foreign key relationship defined, this relation does not exist. Is it possible to create a relationship outside of defining it as a foreign key relation and doing a code regen?

You can create a relationship for fetch intention. Something like:

IEntityRelation customNewRelation = new EntityRelation(CustomerEntityFields.CustomerId, ReportHistoryEntityFields.CustomerId, RelationType.OneToMany);

RelationPredicateBucket bucket = new RelationPredicateBucket();
bucket.Relations.Add(customNewRelation);

You need to do this everywhere you use similar approach. However, if there are many places to do that, I would recommend you create such relation in designer. What is the problem with that? If that is not the case, you can simply use the code I gave above.

Hope helpful wink

David Elizondo | LLBLGen Support Team