Hi Pete,
I asked in the EF forum but the answer I got was wrong ... I finally
found the problem. Now everything compiles.
About Find what you say is since GetAll() returns all records I could
use for example inside the service:
var result = _repo.GetAll().Where(a => a.Published == true);
Instead of:
var result = _repo.Find(a => a.Published == true);
If this is what you meant I think your approach is better.
About partial I was doing everything fine, well at least now compiles.
The problem was with the advice I was getting in EF where they
answered me as I was using Linq To SQL instead of Linq to Entities.
But I was on a Linq to Entities forum.
This said this is my code. I created a simple EF model with only one
Entity: Article. And post also my code.
If you have any suggestion is welcome ... But I think I am making this
right.
using AutoMapper;
using Lab;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Linq;
using System.Data.Objects;
using System.Data.Entity;
using System.Data.EntityClient;
using System.Reflection;
namespace Lab {
class Program {
static void Main(string[] args) {
}
}
public interface ISession {
void Commit();
void Rollback();
} // ISession
public partial class AppEntities : ISession {
public void Commit() {
SaveChanges();
} // Commit
public void Rollback() {
Dispose();
} // Rollback
} // AppEntities
// IRepository
public interface IRepository<T> {
void Create(T o);
void Delete(T o);
//void Find(System.Linq.Expressions.Expression<Func<T, bool>>
predicate);
IQueryable<T> GetAll();
T GetById(int id);
int Update(T o);
} // IRepository
// Repository
public class Repository<T> : IRepository<T> {
private AppEntities context;
public Repository(ISession session) {
if (session == null)
throw new ArgumentNullException("session");
context = session as AppEntities;
}
public void Create(T o) {
var tableName = typeof(T).Name;
context.AddObject(tableName, o);
}
public void Delete(T o) {
var tableName = typeof(T).Name;
context.DeleteObject(o);
}
public IQueryable<T> GetAll() {
var tableName = typeof(T).Name;
return context.CreateQuery<T>(tableName).AsQueryable();
}
public T GetById(int id) {
var tableName = typeof(T).Name;
var key = new EntityKey("AppEntities." + tableName, "Id", id);
var r = (T)context.GetObjectByKey(key);
return r;
}
public int Update(T o) {
var tableName = typeof(T).Name;
var Id = GetPrimaryKeyValue(o);
T currentObject = GetById(Id);
currentObject = o;
context.ApplyPropertyChanges(tableName, currentObject);
return context.SaveChanges();
}
private int GetPrimaryKeyValue(T o) {
int Id = 0;
var properties = typeof(T).GetProperties();
foreach (PropertyInfo p in properties) {
if (string.Compare(p.Name, "Id", true) == 0) {
var r = p.GetValue(o, null).ToString();
Id = int.Parse(r);
break;
}
}
return Id;
}
} // Repository
// Service
public abstract class Service<TModel, T> where TModel : new() where
T : new() {
public Repository<T> _repo;
protected Service(ISession session) {
_repo = new Repository<T>(session);
var tm = Mapper.FindTypeMapFor<T, TModel>();
if (tm == null) {
Mapper.CreateMap<T, TModel>();
}
tm = Mapper.FindTypeMapFor<TModel, T>();
if (tm == null) {
Mapper.CreateMap<TModel, T>();
}
}
public virtual TModel GetById(Int32 id) {
var item = _repo.GetById(id);
var model = Map(item);
return model;
}
public virtual TModel Map(T d) {
return Mapper.Map<T, TModel>(d);
}
public virtual IList<TModel> Map(IList<T> d) {
return Mapper.Map<IList<T>, List<TModel>>(d);
}
} // Service
public class ArticleUI {
public int Id { get; set; }
public String Title { get; set; }
public String Content { get; set; }
}
// ArticleService
public class ArticleService : Service<ArticleUI, Article> {
public ArticleService(ISession session) : base(session) {
}
public IList<ArticleUI> GetPublished() {
var query = _repo.GetAll().Where(a => a.Published == true);
var articles = query.ToList();
return Map(articles);
}
}
}
And what EF generates is the following:
[assembly: global::System.Data.Objects.DataClasses.EdmSchemaAttribute
()]
// Original file name:
// Generation date: 18-09-2009 19:05:56
namespace Lab
{
/// <summary>
/// There are no comments for AppEntities in the schema.
/// </summary>
public partial class AppEntities :
global::System.Data.Objects.ObjectContext
{
/// <summary>
/// Initializes a new AppEntities object using the connection
string found in the 'AppEntities' section of the application
configuration file.
/// </summary>
public AppEntities() :
base("name=AppEntities", "AppEntities")
{
this.OnContextCreated();
}
/// <summary>
/// Initialize a new AppEntities object.
/// </summary>
public AppEntities(string connectionString) :
base(connectionString, "AppEntities")
{
this.OnContextCreated();
}
/// <summary>
/// Initialize a new AppEntities object.
/// </summary>
public AppEntities
(global::System.Data.EntityClient.EntityConnection connection) :
base(connection, "AppEntities")
{
this.OnContextCreated();
}
partial void OnContextCreated();
/// <summary>
/// There are no comments for Articles in the schema.
/// </summary>
public global::System.Data.Objects.ObjectQuery<Article>
Articles
{
get
{
if ((this._Articles == null))
{
this._Articles = base.CreateQuery<Article>
("[Articles]");
}
return this._Articles;
}
}
private global::System.Data.Objects.ObjectQuery<Article>
_Articles;
/// <summary>
/// There are no comments for Articles in the schema.
/// </summary>
public void AddToArticles(Article article)
{
base.AddObject("Articles", article);
}
}
/// <summary>
/// There are no comments for Lab.Article in the schema.
/// </summary>
/// <KeyProperties>
/// Id
/// </KeyProperties>
[global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute
(NamespaceName="Lab", Name="Article")]
[global::System.Runtime.Serialization.DataContractAttribute
(IsReference=true)]
[global::System.Serializable()]
public partial class Article :
global::System.Data.Objects.DataClasses.EntityObject
{
/// <summary>
/// Create a new Article object.
/// </summary>
/// <param name="id">Initial value of Id.</param>
/// <param name="content">Initial value of Content.</param>
/// <param name="created">Initial value of Created.</param>
/// <param name="published">Initial value of Published.</
param>
/// <param name="title">Initial value of Title.</param>
/// <param name="updated">Initial value of Updated.</param>
public static Article CreateArticle(int id, string content,
global::System.DateTime created, bool published, string title,
global::System.DateTime updated)
{
Article article = new Article();
article.Id = id;
article.Content = content;
article.Created = created;
article.Published = published;
article.Title = title;
article.Updated = updated;
return article;
}
/// <summary>
/// There are no comments for Property Id in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute
(EntityKeyProperty=true, IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public int Id
{
get
{
return this._Id;
}
set
{
this.OnIdChanging(value);
this.ReportPropertyChanging("Id");
this._Id =
global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue
(value);
this.ReportPropertyChanged("Id");
this.OnIdChanged();
}
}
private int _Id;
partial void OnIdChanging(int value);
partial void OnIdChanged();
/// <summary>
/// There are no comments for Property Content in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute
(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public string Content
{
get
{
return this._Content;
}
set
{
this.OnContentChanging(value);
this.ReportPropertyChanging("Content");
this._Content =
global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue
(value, false);
this.ReportPropertyChanged("Content");
this.OnContentChanged();
}
}
private string _Content;
partial void OnContentChanging(string value);
partial void OnContentChanged();
/// <summary>
/// There are no comments for Property Created in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute
(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public global::System.DateTime Created
{
get
{
return this._Created;
}
set
{
this.OnCreatedChanging(value);
this.ReportPropertyChanging("Created");
this._Created =
global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue
(value);
this.ReportPropertyChanged("Created");
this.OnCreatedChanged();
}
}
private global::System.DateTime _Created;
partial void OnCreatedChanging(global::System.DateTime value);
partial void OnCreatedChanged();
/// <summary>
/// There are no comments for Property Excerpt in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public string Excerpt
{
get
{
return this._Excerpt;
}
set
{
this.OnExcerptChanging(value);
this.ReportPropertyChanging("Excerpt");
this._Excerpt =
global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue
(value, true);
this.ReportPropertyChanged("Excerpt");
this.OnExcerptChanged();
}
}
private string _Excerpt;
partial void OnExcerptChanging(string value);
partial void OnExcerptChanged();
/// <summary>
/// There are no comments for Property Published in the
schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute
(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public bool Published
{
get
{
return this._Published;
}
set
{
this.OnPublishedChanging(value);
this.ReportPropertyChanging("Published");
this._Published =
global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue
(value);
this.ReportPropertyChanged("Published");
this.OnPublishedChanged();
}
}
private bool _Published;
partial void OnPublishedChanging(bool value);
partial void OnPublishedChanged();
/// <summary>
/// There are no comments for Property Title in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute
(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public string Title
{
get
{
return this._Title;
}
set
{
this.OnTitleChanging(value);
this.ReportPropertyChanging("Title");
this._Title =
global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue
(value, false);
this.ReportPropertyChanged("Title");
this.OnTitleChanged();
}
}
private string _Title;
partial void OnTitleChanging(string value);
partial void OnTitleChanged();
/// <summary>
/// There are no comments for Property Updated in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute
(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
public global::System.DateTime Updated
{
get
{
return this._Updated;
}
set
{
this.OnUpdatedChanging(value);
this.ReportPropertyChanging("Updated");
this._Updated =
global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue
(value);
this.ReportPropertyChanged("Updated");
this.OnUpdatedChanged();
}
}
private global::System.DateTime _Updated;
partial void OnUpdatedChanging(global::System.DateTime value);
partial void OnUpdatedChanged();
}
}
Maybe this might be useful for someone.
Thanks,
Miguel