Hi,
I want to ask a few questions about EF and repository design pattern implementation.
I'm very new to EF and I want to learn more about that.
I already have a database and tables inside of it. So, I don't want to entity frameworks re-generate this tables.(So I have to use DB First approach I think)
I just wanted to do CRUD operations easily.
And I wanted to use this repository pattern with wcf service.
Can I use EF with already created tables?
Thanks in advance.
What I have tried:
First my configuration file(web.config), which is cannot be able to connect database.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http:
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp />
</behavior>
<behavior>
<dataContractSerializer maxItemsInObjectGraph="1000" />
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="BilplasWcfService.BilplasWebService" behaviorConfiguration="ServiceBehavior">
<endpoint binding="webHttpBinding" contract="BilplasWcfService.IBilplasWebService" behaviorConfiguration="web"></endpoint>
</service>
</services>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true" />
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
<connectionStrings>
<!--<add name="StockManagementSystemConnectionString" connectionString="Data Source= DESKTOP-E0NKE43\BILPLASMAIN; Initial Catalog=BILPLAS; User Id= stock; Password= stock1stock2;"/>-->
<add name="StockManagementSystemConnectionString" connectionString="Data Source= DESKTOP-E0NKE43\BILPLASMAIN; Initial Catalog= BILPLAS; User Id= stock; Password= stock1stock2;" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<!--<parameter value="mssqllocaldb" />-->
<parameter value="Data Source= DESKTOP-E0NKE43\BILPLASMAIN; Initial Catalog= BILPLAS; MultipleActiveResultSet= True; User Id= stock; Password= stock1stock2;"/>
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
My DBContext;
public class EFDBContext : DbContext
{
public EFDBContext() : base("name=StockManagementSystemConnectionString") { }
public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
{
return base.Set<TEntity>();
}
public virtual DbSet<WorkCommandProduction> WorkCommandsInProduction { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var typesToRegister = Assembly.GetExecutingAssembly().GetTypes().Where(type => !string.IsNullOrEmpty(type.Namespace)).Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
foreach(var type in typesToRegister)
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Configurations.Add(configurationInstance);
}
base.OnModelCreating(modelBuilder);
}
}
My Generic Repository;
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
protected readonly EFDBContext context;
string errorMessage = string.Empty;
public Repository(EFDBContext context)
{
this.context = context;
}
public TEntity GetbyID(int id)
{
return context.Set<TEntity>().Find(id);
}
public IEnumerable<TEntity> GetAll()
{
try
{
return context.Set<TEntity>().ToList();
}
catch (DbEntityValidationException dbEx)
{
throw new Exception(GetErrorMessage(dbEx), dbEx);
}
}
public void Insert(TEntity entity)
{
try
{
if (entity == null)
throw new ArgumentNullException("entity");
context.Set<TEntity>().Add(entity);
}
catch(DbEntityValidationException dbEx)
{
throw new Exception(GetErrorMessage(dbEx), dbEx);
}
}
public void Delete(TEntity entity)
{
try
{
if (entity == null)
throw new ArgumentNullException("entity");
context.Set<TEntity>().Remove(entity);
}
catch(DbEntityValidationException dbEx)
{
throw new Exception(GetErrorMessage(dbEx), dbEx);
}
}
public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate)
{
return context.Set<TEntity>().Where(predicate);
}
private string GetErrorMessage(DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
errorMessage += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine;
}
}
return errorMessage;
}
My repository for specific to entity
public class WorkCommandProductionRepository : Repository<WorkCommandProduction>, IWorkCommandProductionRepository
{
public WorkCommandProductionRepository(EFDBContext context) : base(context)
{
context.Database.Exists();
string state = context.Database.Connection.State.ToString();
}
public IEnumerable<WorkCommandProduction> GetAllWorkCommandsInProduction(int from, int to)
{
context.Database.Exists();
string state = context.Database.Connection.State.ToString();
return EFDBContext.WorkCommandsInProduction.ToList();
}
public IEnumerable<WorkCommandProduction> GetAllWorkCommandsOutOfProduction(int from, int to)
{
throw new NotImplementedException();
}
public EFDBContext EFDBContext
{
get { return context as EFDBContext; }
}
}
My Unit of Work
public class UnitOfWork : IUnitOfWork
{
private readonly EFDBContext context;
private bool disposed;
private Dictionary<string, object> repositories;
public UnitOfWork(EFDBContext context)
{
this.context = context;
WorkCommandsInProduction = new WorkCommandProductionRepository(this.context);
}
public UnitOfWork()
{
this.context = new EFDBContext();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public IWorkCommandProductionRepository WorkCommandsInProduction { get; private set; }
public void Save()
{
context.SaveChanges();
}
public virtual void Dispose(bool disposing)
{
if(!disposed)
{
if (disposing)
this.context.Dispose();
}
disposed = true;
}
public Repository<TEntity> Repository<TEntity>() where TEntity : WorkCommandProductionBase
{
if (repositories == null)
repositories = new Dictionary<string, object>();
var type = typeof(TEntity).Name;
if(!repositories.ContainsKey(type))
{
var repositoryType = typeof(Repository<>);
var repositoryInstance = Activator.CreateInstance(repositoryType.MakeGenericType(typeof(TEntity)), this.context);
repositories.Add(type, repositoryInstance);
}
return (Repository<TEntity>)repositories[type];
}
}