由于业务决策,我正在从EF7降级到EF6。我看过几个例子,但似乎无法让它发挥作用。
以下是我对EF 7的支持
背景:
public class OwnerContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer(@"Server=server\testdbs;Database=test;Trusted_Connection=True;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Owner>(entity =>
{
entity.ToTable("Owner");
entity.Property(e => e.Id)
.HasMaxLength(50)
.HasColumnType("varchar");
});
}
public virtual DbSet<Owner> Owner { get; set; }
}
所有者模型
public class Owner
{
public int OwnerId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
我如何使用
static void Main(string[] args)
{
using (var context = new OwnerContext())
{
var owner = new Owner
{
Name = "First Name",
Age = 4
};
context.Owner.Add(owner);
context.SaveChanges();
Console.ReadLine();
}
}
我让这个工作没有问题,我在数据库中获得记录。对于EF 6,它有点不同
以下是我对EF6的要求
上下文
public class OwnerContext : DbContext
{
public OwnerContext(string connectionString) : base(connectionString) { }
public OwnerContext()
: this("OwnerConn")
{
}
public virtual DbSet<Owner> Owner{ get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var owner = modelBuilder.Entity<Owner>().ToTable("Owner");
owner.Property(e => e.OwnerId)
.HasMaxLength(50)
.HasColumnType("varchar");
owner.HasKey(u => u.OwnerId);
}
}
模型
public class Owner
{
public int OwnerId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
我如何使用
static void Main(string[] args)
{
try
{
using (var context = new OwnerContext())
{
var person = new Owner
{
Name = "Test Name",
Age = 5
};
context.Owner.Add(person);
context.Entry(person).State = EntityState.Added;
context.SaveChanges();
}
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
Console.ReadLine();
}
的ConnectionString
<connectionStrings>
<add name="OwnerConn" connectionString="Server=server\testdbs;Database=test;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
基于教程,它似乎非常简单。不过,我似乎无法将更改反映在数据库中。但是,当我重新启动控制台应用程序并拉出这样的记录时。
var rows = from a in context.Owner select a
它返回行但我仍然没有在数据库中看到它们。我没有想法,所以希望有人可以提供帮助。