Pergunta

I'm looking into using EF 6 for an upcoming small project I will be doing at a very large organization. Having POCO business objects is essential to me, but all of the options I can find for how to do POCO with EF all seem to rely on auto-generating tools that try to map an entire database structure to POCO objects. We have many databases, hundreds of tables, and hundreds of views, and I'm only looking to use a few of these tables for the time being (and any one project would only hope to use a small subset of them).

Additionally I don't want to necessarily map out the many foreign properties or even some of the normal properties that these tables store. So I'd really like to make these POCO objects by hand and then connect them to EF and let it do the mapping - I'd like to still be able to use an EDMX file and not have to make my own ObjectContext, if possible.

I feel as though this has to be dead simple, but I can't really find any resources on it! If anyone can point me in the right direction that would really be helpful.

Foi útil?

Solução

Entity Framework has a Code First aspect that can just map to existing tables as well. This allows you to use POCOs to represent your tables. You can create Mapping Classes that allow you to separate your POCOs from your database mapping logic.

You can specify if there is a different naming of the table column from the POCO. If there is no difference between the two however, you can omit it.

using ProjectName.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class ProfileMapping : EntityTypeConfiguration<Profile>
{
    public ProfileMapping()
    {
        // Primary Key
        this.HasKey(t => t.Id);

        // Map POCO name to Column Name
        this.Property(t => t.Firstname)
            .HasColumnName("First_Name")
            .HasMaxLength("256");


        // Table Mapping
        this.ToTable("Profiles");

        // Relationships
        this.HasRequired(t => t.Roles);
    }
}

Using the DbContext you can register these mappings.

I would recommend using the Entity Framework Power Tools to generate your DbContext from an existing database.

http://visualstudiogallery.msdn.microsoft.com/72a60b14-1581-4b9b-89f2-846072eff19d

Outras dicas

Check out http://www.asp.net/mvc/tutorials/mvc-5/database-first-development/setting-up-database

Create a edmx for each database and you can select which objects you want to import.

If you have an existing database look at database first.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top