MVC 使用entity framework 访问数据库 发布IIS
2. MVC工程
3. EF 参考
工程架构:
对应实体类:
public class MvcUser { public int Id { get; set; } public string Name { get; set; } public string PassWord { get; set; } public int UserType { get; set; } }
public class UserConfigurature:EntityTypeConfiguration<MvcUser> { public UserConfigurature() { ToTable("UserInformation"); HasKey(x => x.Id); } }
public class EFDbContext:DbContext { public DbSet<MvcUser> Users { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new UserConfigurature()); base.OnModelCreating(modelBuilder); } }
测试代码:(增删改都测试过)延迟加载
/// <summary> /// 插入测试 /// </summary> [TestMethod] public void InsertTest() { context.Users.Add(new MvcUser() { Name = "EF测试", PassWord = "wwwwww", UserType = 1 }); context.SaveChanges(); } [TestMethod] public void ModifyTest() { MvcUser user = context.Users.Find(34); user.Name = "修改后"; context.SaveChanges(); } [TestMethod] public void DeleteTest() { context.Users.Remove(context.Users.FirstOrDefault(x=>x.Id == 34)); context.SaveChanges(); }
测试工程的配置文件<configuration>节点添加:
<connectionStrings> <!--Data Source=(LocalDb)\MSSQLLocalDB;--> <add name="EFDbContext" connectionString=" Server=IP 地址; Initial Catalog=数据库名; User ID=用户名; Password=密码;" providerName="System.Data.SqlClient"/> </connectionStrings>
- integrated security=true 的意思是集成验证,也就是说使用Windows验证的方式去连接到数据库服务器。