Enter only key type (id) or class type for FK in essence, pros and cons

I saw two types of objects, for example:

public class Person
{
    public int Id {get;set;}
    public string Name {get;set;}
    public Country Country {get;set;}
}

and like this:

public class Person
{
    public int Id {get;set;}
    public string Name {get;set;}
    public int CountryId {get;set;}
}

I think the second approach is easier and you get related data only if necessary;
which, in your opinion, is better?

+3
source share
6 answers

It depends on what you want. If you want to get the country identifier, go to the second option. If you really want to use navigation properties and / or lazy loading, skip to the first option.

Personally, I use the Entity Framework and combine the options one and two:

public class Person
{
    public int Id {get;set;}
    public string Name {get;set;}
    public int CountryId {get;set;}
    public Country Country {get;set;}
}

, , . , , , , .

+1

, , - , . ORM.

, CountryId ( , ), . . - , . Person.Country.Id? (, , ).

, , , , , " " . NHibernate, ADO. .

+1

: , ...

Microsoft

, Silverlight, RIA WPF WCF RIA, .

Microsoft

microsoft, Flex/Flash, Java -, ajax, , ( ). .

, , .., App Fabric .., , .

, . , , , .

" " " ", , , , , ..

+1

!

public List<Person> GetPersonsLivingIn(int countryId) {
  return ObjectContext.Persons.Where(x => x.CountryId == countryId).ToList();
}

, , () , ORM, x => x.Country == country. Linq2Sql, , .

, GenericTypeTea, id, . , - .

public List<Person> GetPersonsLivingIn(Country country) {
  return ObjectContext.Persons.Where(x => x.CountryId == country.CountryId).ToList();
}

OO, - , .

+1

, .

( ), , .

+1

STOP!

NHibernate , .

, ( ), :

int countryId = person.Country.Id;

... , Country. NHibernate - , . - - Property Customer, NHibernate , , "person.Country.Id" ID , .

:

string countryName = person.Country.Name;

... , "" .

, :

<many-to-one name="Country" class="Country" column="Country_ID" lazy="proxy" />

( , lazy = "proxy" ).

Simply put, there is no need to map foreign keys in your domain model using NHibernate.

+1
source

Source: https://habr.com/ru/post/1766719/


All Articles