我正在使用 EF 实体实例将数据绑定(bind)到许多 FormView 控件,但我必须求助于这个荒谬的组合,以便在不使用 EntityDataSource 控件的情况下实现我想要的:
propertyHeaderSection.DataSource = new List<PropertyDetailsModel> { _propertyDetails };
我怀疑我将不得不从 FormView 派生出我自己的控件并使其能够接受几乎 POCO 作为数据源。我从哪里开始?
最佳答案
这是我的实现,与 patmortech 的想法相同,但我还发现 BaseDataBoundControl 上的 ValidateDataSource 方法是在运行时引发异常的原因,如果您的数据源不可枚举。
public class CustomFormView : System.Web.UI.WebControls.FormView
{
public override object DataSource
{
get
{
if (!(base.DataSource is IEnumerable))
return new[] {base.DataSource};
return base.DataSource;
}
set
{
base.DataSource = value;
}
}
// This method complains at run time, if the datasource is not
// IListSource, IDataSource or IEnumerbale
protected override void ValidateDataSource(object dataSource)
{
//base.ValidateDataSource(dataSource);
}
}
编辑:
考虑到这个建议,我对检查分配的 DataSource 是否可枚举的方式进行了一些更改。我还设法创建了一个示例应用程序(VS 2010 解决方案)来演示更改。该应用程序可以从 http://raghurana.com/blog/wp-content/attachments/FormViewDataProblem.zip 下载
简而言之,这就是我要检查的内容,以确保现有的数据源可以被枚举或不被枚举:
public static bool CanEnumerate( this object obj )
{
if (obj == null) return false;
Type t = obj.GetType();
return t.IsArray ||
t.Implements(typeof (IEnumerable).FullName) ||
t.Implements(typeof (IListSource).FullName) ||
t.Implements(typeof (IDataSource).FullName);
}
如果这不是所需的功能,请随时提出更多更改。干杯。
关于asp.net - 如何将 Entity Framework 对象数据绑定(bind)到 FormView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7512422/