0

我該如何實現類似以下的內容?具有自定義列名的C#MVC通用存儲庫

public interface IGenericRepository 
{ 
    int id { get; } 

    T GetById<T>() where T : class 
} 

public class GenericRepository : IGenericRepository 
{ 
    //Some code here 

    public T GetById<T>(int tid) where T : class 
    { 
     return from tbl in dataContext.GetTable<T> where tbl.id == tid select tbl; 
    } 
} 

,我想用這個如下:

GenericRepository gr = new GenericRepository(); 
Category cat = gr.GetById<Category>(15); 

當然,在這種用法,tbl.id在GenericRepository給我一個錯誤。

SOLUTION

public class IHasId 
{ 
    public int id { get; set; } 
} 

public interface IGenericRepository 
{ 
    int id { get; } 

    T GetById<T>(int id) where T : IHasId; 
} 

public class GenericRepository : IGenericRepository 
{ 
    public int id 
    { 
     get { throw new NotImplementedException(); } 
    } 

    public T GetById<T>(int id) where T : IHasId 
    { 
     return from tbl in dataContext.GetTable<T> where tbl.id == tid select tbl; 
    } 
} 

而除了這些,別忘了定義這個地方你的模型:

public partial class Category : IHasId { } 

而且用法是:

Repository rep = new Repository(); 
Category cat = rep.GetById<Category>(15); 

回答

1
public class IHasId 
{ 
    public int id { get; set; } 
} 

public interface IGenericRepository<T> 
{ 
    int id { get; } 

    T GetById(int id); 
} 

public class GenericRepository<T> : IGenericRepository<T> where T : IHasId 
{ 
    public int id 
    { 
     get { throw new NotImplementedException(); } 
    } 

    public T GetById(int id) 
    { 
     return from tbl in dataContext.GetTable<T> where tbl.id == tid select tbl; 
    } 
} 
+0

該死!我終於明白了這個問題,除了這些代碼之外,我必須爲每個使用的實體創建一個部分類。說,我有類別表,我不得不創建一個IBase繼承的公共部分類別!多謝,夥計!! – Shaokan

+1

IHasId繼承遺憾:) – Shaokan

1

你得到這個錯誤,因爲你接受每個類where T : class。一個班級沒有這個屬性。

創建抽象類或接口以確保此屬性存在並將where T : class更改爲where T : IHasIdProperty

+0

但是當我用gr.GetById (15),它給了我該說,這是不可能的類別轉換爲IhasIdProperty,@dknaack – Shaokan

+0

其實,@dknaack一個錯誤,當我改變where子句爲其中T:IHasID,那麼dataContext.GetTable 將給我一個錯誤 – Shaokan

+0

這是一個新的答案與更改的存儲庫。 – dknaack

2

這裏有幾個問題 - 第一個是你所匹配的泛型類是一個類,但是一個類沒有叫做'id'的屬性。你需要讓你的類的類實現暴露的「身份證」屬性的接口:

public interface IIdentity 
{ 
    int identity { get; set; } 
} 

public class Category : IIdentity 
{ 
    public int identity{ get; set; } 
} 

我不知道爲什麼你已經暴露的「身份證」作爲IGenericRepository接口上的屬性 - 當然這是應該作爲傳遞給find方法的參數(如您的實現所示)。您還需要在「GetById」的方法來改變限制:

where T : class 

用我上面提出的界面類似

where T : IIdentity 

+0

感謝您的回答@Dave。但問題是,當我將T:class更改爲IIdentity時,dataContext.GetTable 將不起作用,因爲T在此上下文中像表名變量一樣工作。或者我不能得到這個工作,我不知道... – Shaokan

+0

你會得到什麼錯誤信息? – Dave

+0

好吧,我已經解決了這個問題,我會編輯我的問題:) – Shaokan