我有一个项目即将开始,所以我决定查看实体框架。如果我不必创建数据管理器,我认为这将是要走的路,如果它有效。我看到很多关于它的事情,但没有一个是清楚的。
它创建了这个类
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。我没有这样的Component类。我花了半天时间研究这个问题,并开始怀疑实体框架是否是微软Bob的堂兄。除非有人能告诉我我缺少什么,否则我将不得不编写自己的数据管理员。
答案 0 :(得分:0)
我一步一步地恢复:
1 - 创建一个控制台项目。
2 - 使用Nuget安装EF: Install-Package EntityFramework
3 - 创建SalesRepresentative:
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)中,您应该自定义连接字符串。