本文将从以下几个方面介绍efcore dbfirst的使用方法,并附带对应代码示例。
一、数据库连接
在使用efcore dbfirst前,需要先创建数据库连接。可以通过添加以下代码来创建数据库连接。
public class ApplicationDbContext : DbContext { public virtual DbSet<Person> persons { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer(Configuration.GetConnectionString("DatabaseConnection")); } } }
其中person是要操作的表,DatabaseConnection是在appsettings.json文件中定义的连接字符串。
二、基本操作
1、增加数据
在efcore dbfirst中,增加数据需要先在数据库中添加数据,然后使用以下代码将数据同步到efcore中。
using (var context = new ApplicationDbContext()) { var person = new Person { Name = "John Smith", Age = 30 }; context.persons.Add(person); context.SaveChanges(); }
2、查询数据
可以使用以下代码查询person表中的所有数据。
using (var context = new ApplicationDbContext()) { var persons = context.persons.ToList(); }
查询特定数据可以使用以下代码。
using (var context = new ApplicationDbContext()) { var person = context.persons.Where(p => p.Age == 30).FirstOrDefault(); }
3、修改数据
可以使用以下代码修改person表中的数据。
using (var context = new ApplicationDbContext()) { var person = context.persons.Where(p => p.Id == 1).FirstOrDefault(); person.Name = "Tom Smith"; context.SaveChanges(); }
在上述代码中,首先查询id为1的person数据,然后将其姓名修改为Tom Smith,最后保存更改。
三、操作多个表
在efcore dbfirst中,可以使用linq对多个表进行联合查询或关联操作。以下代码示例可以查询person表和address表之间的关联。
using (var context = new ApplicationDbContext()) { var persons = context.persons .Join(context.addresses, p => p.Id, a => a.PersonId, (p, a) => new { Id = p.Id, Name = p.Name, Age = p.Age, Address = a.AddressLine }) .ToList(); }
在上述代码中,使用Join方法将person表和address表按照共有的PersonId字段进行联接。
四、使用存储过程
可以使用以下代码执行sql Server中的存储过程。
using (var context = new ApplicationDbContext()) { var result = context.Database .ExecuteSqlCommand("EXEC [dbo].[usp_UpdatePersonAgeByAddress] @address", new SqlParameter("@address", "No.123 Main Street")); }
在上述代码中,使用ExecuteSqlCommand方法执行存储过程usp_UpdatePersonAgeByAddress,其中@address为存储过程参数,值为No.123 Main Street。
五、使用事务
以下代码示例演示了在efcore dbfirst中使用事务。
using (var context = new ApplicationDbContext()) { using (var transaction = context.Database.BeginTransaction()) { try { var person1 = new Person { Name = "John Smith", Age = 30 }; var person2 = new Person { Name = "Tom Smith", Age = 25 }; context.persons.Add(person1); context.SaveChanges(); context.persons.Add(person2); context.SaveChanges(); transaction.Commit(); } catch(Exception) { transaction.Rollback(); } } }
在上述代码中,创建了一个事务,分别插入两条数据,并在事务能够成功提交的情况下提交事务,否则进行回滚。