Dapper in 1-1 grating where in class there is no foreign key

Asked

Viewed 106 times

0

When working with ORM it is common (Will it be mandatory?) to create the model classes as if they were a mirror of the tables of the bank. But I have a different case and I was wondering if Dapper works that way. In the bank I have the tables. Produto and Fornecedor

Fornecedor:

nome varchar(50)
tel  varchar(11)
cpf  varchar(11) PRIMARY KEY

Produto:

codebar    varchar(13)
nome       varchar(50)
preco      money
custo      money
estoque    int
fornecedor varchar(11) FOREIGN KEY ProdutoToFornecedor(fornecedor) REFERENCES (Fornecedor.cpf)

Note: Ignore SQL, it is fictitious only for demonstration purposes.

The class Produto has the type attribute Fornecedor but does not have an attribute that would represent the foreign key with the supplier.

public class Fornecedor
{
    public string Nome {get; set;}
    public string Tel  {get; set;}
    public string cpf  {get; set;}
}

public class Produto
{
    public string     CodeBar   {get; set;}
    public string     Nome      {get; set;}
    public decimal    Preco     {get; set;}
    public decimal    Custo     {get; set;}
    public int        Estoque   {get; set;}
    public Fornecedor Fornec    {get; set;}
}

As can be seen Produto has a property of the type Fornecedor but there isn’t another one that would be the foreign key to the table Fornecedor. I honestly never understood the necessity of it. If an object Produto will have a property that is an object of type Fornecedor who in turn already owns the property Cpf which is the table primary key, because I would still need to have an attribute on Produto which refers to foreign key to Fornecedor? That is to say:

public class Produto
{
    public string     CodeBar   {get; set;}
    public string     Nome      {get; set;}
    public decimal    Preco     {get; set;}
    public decimal    Custo     {get; set;}
    public int        Estoque   {get; set;}
    public string     FornecId  {get; set;}
    public Fornecedor Fornec    {get; set;}
}

It seems redundant to me.

To use ORM, in case Dapper is there any way to escape from it? That is, use the property Fornec which is an object Fornecedor and already has the attribute Cpf?

  • 1
  • 1

    Yes. When you do the query it returns a dto or Objectvalue only with the fields you need and in the most appropriate structure. The Matheus link helps you understand how to do this.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.