【问题标题】:How to use a class created by the entity framework [closed]如何使用实体框架创建的类[关闭]
【发布时间】:2017-01-02 08:35:15
【问题描述】:

我有一个项目即将推出,所以我决定研究实体框架。如果我不必创建数据管理器,我认为这将是可行的方法,如果可行的话。我看到了很多关于它的东西,但没有一个是清楚的。

它创建了这个类

namespace EFTest
{
    using System;
    using System.Collections.Generic;

    public partial class SalesRepresentative
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string CellPhone { get; set; }
    }
}

如何使用它?寻找例子我看到这样的事情:

using (var ctx = new Context())
{
    Employee emp = new Employee() { name = "Prashant" };
    ctx.Employees.Add(emp);
    ctx.SaveChanges();
}

我有一个名为 Model.Comntext 的文件,其中没有上下文类。我尝试将其更改为 dBContext,但这也不起作用。

我还发现了这个:

CustomersComponent custc = new CustomersComponent();
Customers cust = custc.getCustomer(Id);
txtName.Text = cust.Name;
ddlCategories.SelectedValue = cust.Category.Id.ToString();

嗯,它有一个 Customer 和一个 CustomerComponent。我没有这样的组件类。我花了半天时间研究这个问题,并开始怀疑 Entity Framework 是否是 Microsoft Bob 的表亲。除非有人能告诉我我缺少什么,否则我将不得不编写自己的数据管理器。

【问题讨论】:

    标签: c# .net vb.net entity-framework


    【解决方案1】:

    我一步步恢复:

    1 - 创建一个控制台项目。

    2 - 使用 Nuget 安装 EF:Install-Package EntityFramework

    3 - 创建销售代表:

    namespace EF {
        public partial class SalesRepresentative {
            public int ID { get; set; }
            public string Name { get; set; }
            public string Email { get; set; }
            public string CellPhone { get; set; }
        }
    }
    

    4 - 创建 GeneralContext

    namespace EF {
        public class GeneralContext: DbContext {
    
            public DbSet<SalesRepresentative> SalesRepresentatives { get; set; }
        }
    }
    

    5 - 所以:

    namespace EF {
        class Program {
            static void Main(string[] args) {
    
                using (var ctx = new GeneralContext()) {
                    SalesRepresentative emp = new SalesRepresentative() { Name = "Prashant" };
                    ctx.SalesRepresentatives.Add(emp);
                    ctx.SaveChanges();
                }
            }
        }
    }
    

    注意:在 App.config 文件(或 web.config)中,您应该自定义连接字符串。

    【讨论】:

    • 谢谢塞巴,+1。我使用的教程从未提及 GeneralContext 类。当您尝试学习某些东西时,很难区分完整与不完整。你让我前进,再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多