实体框架6 dbContext不保存更改

时间:2016-02-24 08:21:23

标签: entity-framework asp.net-mvc-5 asp.net-identity

在我们的MVC 5项目中,我们的数据库上下文在AccountController中实例化,就像这样

    private CustomersContext _customersContext;

    public CustomersContext CustContext
    {
        get
        {
            return _customersContext ?? new CustomersContext();
        }
        private set
        {
            _customersContext = value;
        }
    }

每个客户都有多个来源推荐。下面的例程将引荐来源的UserId更改为新用户。

        var referralList = CustContext.Referrals.Where(d => d.UserId == membershipUser.Id);
        foreach (Referral referral in referralList)
        {
            referral.UserId = newUser.Id;
        }

通过代码逐步执行我可以看到referral.UserId正在更新。然而

var result = await CustContext.SaveChangesAsync();

返回0.数据库未更新。

CustomersContext看起来像这样

{
public partial class CustomersContext : IdentityDbContext<ApplicationUser>//, ICustomersContext
{

    public CustomersContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static CustomersContext Create()
    {
        return new CustomersContext();
    }

    public virtual DbSet<ReferralSource> ReferralSources { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<ApplicationUser>()
            .HasMany(e => e.Referrals)
            .WithRequired(e => e.User)
            .HasForeignKey(e => e.UserId)
            .WillCascadeOnDelete(false);

我没有看到SQL Profiler中发出的任何sql。为什么数据库上下文没有保存更改?

2 个答案:

答案 0 :(得分:1)

在调用 (define (inseq seq n m) (cond ((= 0 n) #f) (else (or (= m (seq n)) (inseq seq (- n 1) m))))) (define (lower n) (- (rec (- n 1)) n)) (define (higher n) (+ (rec (- n 1)) n)) (define (rec n) (cond ((= 1 n) 1) ((and (> (lower n) 0) (not (inseq rec (- n 1) (lower n)))) (lower n)) (else (higher n)))) 之前,您需要设置要修改的实体的状态。像这样的东西:

var result = await CustContext.SaveChangesAsync();

答案 1 :(得分:1)

@Issac提供的答案并没有解决我的问题,但它确实让我走上了解决方案的道路。错误

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

建议有多个dbContext实例。我从CTOR中删除了上下文,并在using语句中实例化了上下文

using (CustomersContext customersContext = new CustomersContext())
{
    var referralList = customersContext.Referrals.Where(d => d.UserId == membershipUser.Id);
    foreach (Referral referral in referralList)
    {
        referral.UserId = newUser.Id;
    }
    var result = await customersContext.SaveChangesAsync();
}

现在一切都是tickety-boo