user721146
user721146

Reputation: 65

Entity Framework, Dependency Injection and Shared Objects

I want to use Dependency in a project that uses the Entity Framework. The Entity Framework creates classes based on the table structures using the partial keyword. The Service Interfaces that I create work with these classes.

I would like to move these classes to a project named Shared Objects so that the apps do not need to include the database project directly to work. Is it possible to move the objects out? I am concerned because they are auto generated.

Upvotes: 2

Views: 121

Answers (1)

Jesus Angulo
Jesus Angulo

Reputation: 2666

Yes, you can add a class library project and move the template to this project. The T4 file named like your EDMX file, wich don't end with '.Context.tt'.

A easy way to do this is , add a empty text template file to your class library project and paste the content of NameOfYourEDMXFile.tt, then delete the original text templatefile and finally change the value inputFile const inside the new text template to match the EDMX location.

<#@ template language="C#" debug="false" hostspecific="true"#>
<#@ include file="EF6.Utility.CS.ttinclude"#><#@ 
 output extension=".cs"#><#

 //const string inputFile = @"SampleModel.edmx"; //ORIGINAL
const string inputFile = @"..\SNE.Console\SampleModel.edmx";

If you try to build your project you would receive an error about a missing directive or using, fix the NameOfYourEDMXFile.context.tt to include the new location of your entities classes, something like this (line 46 aprox on EF6 text template):

#>
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;

//line 46 of SampleEDMX.Context.tt
using Sample.Shared; //I added this using to fix the build

<#
if (container.FunctionImports.Any())
{
#>

And it's all. If you don't like this approach, you can check Code-First approch I recommend it. https://msdn.microsoft.com/en-us/data/jj193542.aspx

Upvotes: 2

Related Questions