【问题标题】:Can't retrieve ManyToMany field value in ASP.NET Dynamic Data无法在 ASP.NET 动态数据中检索 ManyToMany 字段值
【发布时间】:2016-10-10 05:57:42
【问题描述】:

我有 2 个模型 PosTransactionModelPosItemModel,它们通过 EntityFramework6 基于 Postgresql 构建,它们将每个模型引用为 ManyToMany 关系。

public class PosTransactionModel
{
    public int Id { get; set; }
    public ICollection<PosItemModel> SaleItems { get; set; }
    ...
    ...
}

public class PosItemModel
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]       
    public int ItemId { get; set; }
    public ICollection<PosTransactionModel> SoldInPosTransactions { get; set; }
}

我可以看到已经成功创建了 3 个表来维护数据和关系:

在数据库表中填写了一些测试数据,我可以看到PosTransactionModel及其SaleItems数据可以通过WebAPI接口正确发布,客户端测试http客户端可以得到正确的JSON数据:

现在,我正在尝试构建一个管理站点以通过 ASP.NET 动态数据模板管理这些数据,问题是 ManyToMany SaleItems 字段总是针对测试数据为空:

这是ManyToManyField的默认模板代码:

public partial class ManyToManyField : System.Web.DynamicData.FieldTemplateUserControl
{
    protected override void OnDataBinding(EventArgs e)
    {
        base.OnDataBinding(e);

        object entity;
        ICustomTypeDescriptor rowDescriptor = Row as ICustomTypeDescriptor;
        if (rowDescriptor != null)
        {
            entity = rowDescriptor.GetPropertyOwner(null);
        }
        else
        {
            entity = Row;
        }

        var entityCollection = Column.EntityTypeProperty.GetValue(entity, null);
        var realEntityCollection = entityCollection as RelatedEnd;
        if (realEntityCollection != null && !realEntityCollection.IsLoaded)
        {
            realEntityCollection.Load();
        }

        Repeater1.DataSource = entityCollection;
        Repeater1.DataBind();
    }

    public override Control DataControl
    {
        get
        {
            return Repeater1;
        }
    }

}

通过调试,我可以看到entityCollection 始终为空,我错过了什么?

【问题讨论】:

    标签: c# asp.net entity-framework asp.net-dynamic-data


    【解决方案1】:

    不知道什么是ASP.NET 动态数据模板。但是在您的模型中,ICollection&lt;T&gt; 应该添加 virtual 前缀,因为您可以通过延迟加载获取这些模型集合(确保 Configuration.LazyLoadingEnabled 在您的 DBContext 中不为 false)。可能与您的动态数据模板有关。

    【讨论】:

    【解决方案2】:

    我认为问题出在您的数据模型上 我没有将 EF6 与 DD 一起使用,因为对我来说存在一些问题(在保存更改时运行业务逻辑不适用于 EF 数据源),除了我能想到的是否与您的模型有关,因为 M2M 字段模板在 EF5 和 EF6 数据库优先模式下工作正常。

    【讨论】:

    • 正如我所说,我正在使用另一个 ASP.NET WEB API 项目来测试模型,一切看起来都不错,结果也粘贴了屏幕截图。所以我认为这不是 EF6 模型的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2012-02-01
    • 2013-06-27
    • 2013-08-12
    相关资源
    最近更新 更多