OrmLite [Reference] vs [ForeignKey(typeof(T))] vs [References(typeof(T))]

Given these 2 simples classes:

public class Person
{
    [AutoId]
    public Guid Id { get; set; }
    
    [Unique]
    [Required]
    public string Name { get; set; }
    
    [Reference]
    public PhoneNumber PhoneNumber { get; set; } 
}

public class PhoneNumber
{
    [AutoId]
    public Guid Id { get; set; }
    
    public Guid PersonId { get; set; }
    
    [Unique]
    [Required]
    [Index]
    public string Number { get; set; }
}

When persisting the above code no foreign keys seems to be created. Is this the default behaviour or am I doing something wrong?

I’ve ended up modifiying the class like so:

public class PhoneNumber
{
    [AutoId]
    public Guid Id { get; set; }
    
    [References(typeof(Person))]
    public Guid PersonId { get; set; }
    
    [Unique]
    [Required]
    [Index]
    public string Number { get; set; }
}

And the foreign key is created.

Is this the usual way this should be done?

I also saw on the forum this variant:

public class PhoneNumber
{
    [AutoId]
    public Guid Id { get; set; }
    
    [ForeignKey(typeof(Person))]
    public Guid PersonId { get; set; }
    
    [Unique]
    [Required]
    [Index]
    public string Number { get; set; }
}

What’s the difference?

Thanks.

It’s by design, the [Reference] attribute is used to define POCO relationships for usage in POCO Reference APIs which is defined on the complex type reference, not the foreign key property.

Either the Foreign Key or References Attributes is used to define foreign key properties, [References] is more generic and used to define relationships in other data stores like Poco Dynamo whilst [ForeignKey] is just for RDBMS/OrmLite & has additional customization like defining cascading behavior.

Personally I’d blob localized attribute data like phone numbers and avoid the unnecessary tables & additional queries, I definitely wouldn’t be using Guids which takes up more space then the actual data.

Super thanks.

The above classes are not from my actual application I just made a simple example to better understand.

It’s a multitenant system and we will consolidate all records at one point in a master database so that’s why I went with the guid, at least for now, merging everything will be easier.

But since all the tables have at least one other unique identifier I could always migrate the data anyway.

Thanks for the usual fast reply. Most appreciated.