Use Existing Database with Entity Framework

0

I need help to find out if there is a way to use an existing database with Entity Framework without having to use Visual Studio import, and without using Database First because I do not want tie my code, because I think that way it gets harder to maintain.

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

    
asked by anonymous 07.10.2014 / 21:35

1 answer

4

Possible, yes, but you have to look at some things:

1. You need to have some mapped domain

When I refer to the domain, I mean your system has a class for each collection (or table) that your system uses, and each object represents a record of your collection (or table).

2. You will need to either indicate following a nomenclature, or use decorative 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; }
}

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

Or else:

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

Or:

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 how the relationship between your entities is

Basically they are 3:

  • 1 to 1;
  • 1 for N;
  • N to 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 for N

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

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

N for 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; }
}
    
07.10.2014 / 21:53