Using Existing Database with Entity Framework

Asked

Viewed 159 times

0

I am in need of a help to know if there is a way to use an existing database with Entity Framework without having to use the Visual Studio import, and without using the Database First because I don’t want to tie my code, because I think that way it’s harder to maintain.

I would like to somehow use the database I already have and use it with the Entity Framework.

  • Goes by Fluent Nhibernate

1 answer

4

Possible, it is, but you have to pay attention to a few things:

1. You need to have some domain mapped

When I refer to domain, I refer to your system having a class for each collection (or table) that your system uses, with each object representing a record of your collection (or table).

2. You will need to specify following a nomenclature, or use decoration attributes to make the Entity Framework understand your domain

The Entity Framework understands a domain object that is in the following form:

public class MeuObjeto
{
    public int MeuObjetoId { get; set; }
}

He understands that MeuObjetoId is a primary key of a collection (or table) called MeuObjeto.

Or else:

public class MeuObjeto
{
    public int Id { get; set; }
}

Or else:

public class MeuObjeto
{
    [Key]
    public int MinhaColunaDeIdPersonalizada { get; set; }
}

[Key] indicates which property will be treated as the primary key.

3. You will need to tell us what the relationship between your entities is like

Basically there are 3:

  • 1 to 1;
  • 1-N;
  • N para N.

1 to 1

public class MeuObjeto
{
    [Key]
    public int MeuObjetoId { get; set; }
    public int OutroObjetoId { get; set; }

    public virtual OutroObjeto OutroObjeto { get; set; }
}

1-N

public class MeuObjeto
{
    [Key]
    public int MeuObjetoId { get; set; }

    public virtual ICollection<MeuObjetoDetalhe> MeuObjetoDetalhes { get; set; }
}

N para N

public class MeuObjeto
{
    [Key]
    public int MeuObjetoId { get; set; }

    public virtual ICollection<AssociacaoObjeto> AssociacaoObjetos { get; set; }
}

public class OutroObjeto
{
    [Key]
    public int OutroObjetoId { get; set; }

    public virtual ICollection<AssociacaoObjeto> AssociacaoObjetos { get; set; }
}

public class AssociacaoObjeto
{
    [Key]
    public int AssociacaoObjetoId { get; set; }
    public int OutroObjetoId { get; set; }
    public int MeuObjetoId { get; set; }

    public virtual MeuObjeto MeuObjeto { get; set; }
    public virtual OutroObjeto OutroObjeto { get; set; }
}

Browser other questions tagged

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