[英]Using Entity Framework with “dynamic” entity?
例如,我有3个实体:产品,工具,设备。 它们都具有“id”和“Name”属性。 现在我尝试编写一个方法来将实体的数据填充到组合框中。 但我现在不知道如何创建一个可以将任何实体传递给它的方法。 类似下面的代码:
private comboBox FillCombobox(List<EntityType>)
{
using (dowacodbEntities dowacodbEntities = new dowacodbEntities())
{
comboBox comboBox = new comboBox();
List<EntityType> EntityList = dowacodbEntities.EntityType.ToList();
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("Name");
dt.Rows.Add(-1, "Choose one option");
foreach (EntityType Entity in EntityList)
{
dt.Rows.Add(Entity.id, Entity.Name);
}
comboBox.ValueMember = dt.Columns[0].ColumnName;
comboBox.DisplayMember = dt.Columns[1].ColumnName;
comboBox.DataSource = dt;
return combobox;
}
}
哪个EntityType可以是产品 , 工具或设备 。
我对我们使用的ASP.NET页面有一个类似的基本实体控件,我们遵循Nathan Quirynen的建议。 在您的情况下,有一个基本实体控件,它传递给子类的属性ID和Name。 通过这种控制,我们加载相同的下拉,然后用于订单,设备和所有类型的其他实体。
public interface EntityLoader<T> where T : CommonEntity
{
/*Load all the entities for the list*/
List<T> LoadEntities();
/*Load the single selected entity by its ID*/
T LoadSingleEntity(String ID)
}
/*Common Entity to inherit*/
public class CommonEntity
{
private String _entityID;
private String _entityName;
/*Unique ID of the entity*/
public String ID
{
get { return(_entityID);}
set { _entityID = value;}
}
/*Entity Name*/
public String Name
{
get { return(_entityName); }
set { _entityName = value; }
}
}
public EntityComboBox<T> where T : CommonEntity
{
private comboBox FillCombobox(EntityLoader<T> dataLayer)
{
comboBox comboBox = new comboBox();
List<EntityType> EntityList = dataLayer.LoadEntities();
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("Name");
dt.Rows.Add(-1, "Choose one option");
foreach (EntityType Entity in EntityList)
{
dt.Rows.Add(Entity.ID, Entity.Name);
}
comboBox.ValueMember = dt.Columns[0].ColumnName;
comboBox.DisplayMember = dt.Columns[1].ColumnName;
comboBox.DataSource = dt;
return combobox;
}
}
定义界面:
public interface IBaseEntity
{
int Id { get; }
string Name { get; }
}
在您的Product
, Tool
和Device
类中实现该接口(如果实体是自动生成的,则可以通过部分部分实现)并将您的方法定义为:
private ... FillCombobox<T>(...) where T : class, IBaseEntity
{
using (var context = new Context())
{
var entities = context.CreateObjectSet<T>().ToList();
...
foreach (IBaseEntity entity in entities)
{
dt.Rows.Add(entity.Id, entity.Name);
}
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.