簡體   English   中英

如果我在實體框架代碼第一方法中從 static 方法保存數據,為什么記錄沒有保存在數據庫中?

[英]Why record is not being saved in database if i save data from static method in entity framework code first approach?

我是實體框架代碼優先方法的新手。 所以請多多包涵。

當我從 MVC controller 操作方法調用ProductRepository class 的Add方法時,數據庫中的數據沒有更新。

public class UserProfile
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
}
public class Product
{
    [Key]
    public int Id { get; set; }
    public string Category { get; set; }
    public int UserId { get; set; }
    [ForeignKey("UserId")]
    public UserProfile User { get; set; }
}
public class FarmingDbContext: DbContext
{
    public FarmingDbContext():base("name=FarmerSiteConn"){}
    public DbSet<UserProfile> UserProfileTable { get; set; }
    public DbSet<Product> ProductTable { get; set; }
}
public static class ProductRepository
{
    private static FarmingDbContext Repository
    {
        get
        {
            return new FarmingDbContext();
        }
    }

    public static void Add(Product product)
    {
        Repository.ProductTable.Add(product);
        Repository.SaveChanges();
    }
}

但是當我如下替換上面的Add方法時,數據正在更新。

public static void Add(Product product)
{
    var Repository = new FarmingDbContext();
    Repository.ProductTable.Add(product);
    Repository.SaveChanges();
}

那么這個問題背后的原因是什么,請您幫助我嗎?

提前致謝。

每次調用 Get (Repository) 方法時,都是在創建 DbContext。 這意味着您每次都提供一個新實例(本質上是新連接)。

 private static FarmingDbContext Repository
    {
        get
        {
            return new FarmingDbContext();
        }
    }

你的來電:

public static void Add(Product product)
{
    Repository.ProductTable.Add(product);
    Repository.SaveChanges();
}

是在做:

(new FarmingDbContext()).Add(product);
(new FarmingDbContext()).SaveChanges();

您需要更新您的存儲庫中的 Get 方法以返回相同的實例,或者將您的初始實例分配給一個變量。 使用與調用 Save 的上下文相同的上下文非常重要。

類似的東西應該可以工作:

 public static void Add(Product product)
    {
        using (var repo = ProductRepository.Repository) 
        {
           repo.ProductTable.Add(product);
           repo.SaveChanges();
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM