引用MVC CodeFirst项目的DynamicData应用程序中的实体DataSource控件

时间:2012-01-09 05:17:39

标签: asp.net-mvc entity-framework datasource dynamic-data entitydatasource

我将动态数据Web应用程序添加为MVC 3应用程序的第二个项目。动态数据应用程序在MVC 3应用程序(代码优先)中引用派生的EF 4.1上下文。

DefaultModel.RegisterContext(
    new EFCodeFirstDataModelProvider(() => new MvcApplication1.Models.Context()),
    new ContextConfiguration() { ScaffoldAllTables = true });

我想尝试动态GridView控件,但我不明白如何配置DataSource控件。我的MVC应用程序的连接字符串不适用于该控件。即使在构建之后,控件的配置向导中也没有显示任何内容。我完全是webforms / datasource文盲。我离开这里了吗?我该怎么做?

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication1.DynamicData.CustomPages.WebUserControl1" %>

<asp:GridView ID="GridView1" runat="server">
</asp:GridView>

<asp:DynamicDataManager ID="DynamicDataManager1" runat="server" />
    <DataControlReference ControlID="GridView1"/>
</asp:DynamicDataManager>

<asp:EntityDataSource ID="EntityDataSource1" runat="server">
</asp:EntityDataSource>

2 个答案:

答案 0 :(得分:1)

EntityDataSource控件需要ObjectContext(Database First上下文),而不是DbContext(Code First上下文)。本教程展示了如何使用EntityDataSource并且不到一年的时间: http://www.asp.net/web-forms/tutorials/getting-started-with-ef

答案 1 :(得分:1)

DD模板落后了。

将其添加到文件中:

using System.Linq;
using System.Web.DynamicData;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
public static class ModeContainer<OC> where OC : ObjectContext
{
    private static MetaModel model = new MetaModel();
    static ModeContainer() { model.RegisterContext(typeof(OC), new ContextConfiguration() { ScaffoldAllTables = true }); }
    public static MetaModel Model { get { return model; } }
    public static MetaTable Table<EO>() where EO : EntityObject { return Model.Tables.First(x => x.EntityType == typeof(EO)); }
}

然后Global可以包含这个:

routes.Add(new DynamicDataRoute("{table}/{action}.aspx")
{
    Constraints = new RouteValueDictionary(new { action = "List|Details|Edit|Insert" }),
    Model = ModeContainer<ContactsModel.ContactsEntities>.Model
});

然后你可以在页面中做这样的事情,在路线之外使用动态:

protected void Page_Init(object sender, EventArgs e)
{
    MetaTable table = ModeContainer<ContactsModel.ContactsEntities>.Table<Person>();
    GridView1.SetMetaTable(table);
}

像这样的网格和源代码:

<asp:GridView ID="GridView1" runat="server" DataKeyNames="Id" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
    <SelectedRowStyle BackColor="Azure" />
    <Columns>
        <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" />
        <asp:DynamicField DataField="Contacts" />
        <asp:DynamicField DataField="Addresses" />
    </Columns>
</asp:GridView>


<asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=ContactsEntities" DefaultContainerName="ContactsEntities" EntitySetName="People" EnableDelete="True" EnableInsert="True" EnableUpdate="True" EntityTypeFilter="Person">
</asp:EntityDataSource>