如何使用实体框架创建的类
本文关键字:创建 框架 何使用 实体 | 更新日期: 2023-09-27 18:04: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的文件。上下文中没有上下文类。我试着将其更改为dBContext,但这也不起作用。
我还发现了这个:
CustomersComponent custc = new CustomersComponent();
Customers cust = custc.getCustomer(Id);
txtName.Text = cust.Name;
ddlCategories.SelectedValue = cust.Category.Id.ToString();
它有一个Customer和一个CustomerComponent。我没有这样的Component类。我花了半天时间研究这个问题,开始怀疑实体框架是不是微软Bob的表亲。除非有人能告诉我我错过了什么,否则我将不得不编写自己的数据管理器。
我一步一步地继续:
1 -创建控制台项目。
2 -使用Nuget安装EF: Install- package EntityFramework
3 - Create 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 - Create GeneralContext
namespace EF {
public class GeneralContext: DbContext {
public DbSet<SalesRepresentative> SalesRepresentatives { get; set; }
}
}
5 - So:
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)中,你应该自定义连接字符串。