Two Foreign key in the same EF column

Asked

Viewed 218 times

0

I have a question, I am programming with . NET MVC using the Entity Framework. At the moment I have:

class Produto
{
    public int ProdutoId { get; set; }
    public string Nome { get; set; }
    public string Descricao { get; set; }

    public virtual UsuarioSistema CadastradoPor { get; set; }
    public virtual UsuarioVisitante CadastradoPor { get; set; }

}

The problem is: the 'Registered' field must have the FK of the User Entity OR Usersvisitor.

The User Entity System has many more attributes than the Visiting User Entity, so they are separate.

But even the Usersvisitor being simple and limited, it can also register a product. How should I do the relationship in the entity Product?

class UsuarioVisitante : Usuario
{
    public virtual Fornecedor Fornecedor { get; set; }
    public virtual ICollection<Produto> Produtos { get; set; }
}
  • You have a table for Usersystem and another for Usersvisitor?

  • That, a table User System, User and Product. I did not assemble together because Usuariosistema has many other attributes that are not necessary for Usuariovisitante.

  • I mean the same database... And in the Product table, you have a "Registered" column for system user and another for visiting user?

  • No, that’s the question. I didn’t want to make two columns, because the product will be registered by a Userssystem or Usersvisitor. Understand? The Registered column should receive a key Foreign from Userssystem or Usersvisitor.

  • And how will you know when a Registered is from one or the other

1 answer

0

So you are confusing some things. EF with Entity, Table with Class and Attribute with Column.

First:

public virtual UsuarioSistema CadastradoPor { get; set; }
public virtual UsuarioVisitante CadastradoPor { get; set; }

You can’t have two Attributes with the same name Class, just as it cannot declare the same variable twice in the same scope.

According to:

In the database you cannot have a single column, [CriadoPor] with FK for both UsuarioSistema and UsuarioVisitante. I suspect that the FK be for the Table [Usuario] that must have a Column [Tipo] that you use to differentiate whether it is "System" or "Visitor"

Browser other questions tagged

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