来自另一个DbContext的ASP.NET Web API标识属性

时间:2016-08-22 18:37:42

标签: c# asp.net asp.net-mvc entity-framework asp.net-web-api

我的ASP.NET Web API项目中有StoreUser个身份,StoreDbContext 我有Product模型和DbSet

的地方

这是我的Product

public class Product
{
    public int Id { get; set; }
    public string CodeName { get; set; }
    public decimal Cost { get; set; }
    public decimal Discount { get; set; }
    public int SoldCount { get; set; }
    public string SellerId { get; set; }
    public virtual StoreUser Seller { get; set; }
    public virtual List<ProductImage> Images { get; set; }
    public virtual List<Category> Categories { get; set; }
    public virtual List<ProductText> Texts { get; set; }
}

这是我的StoreDbContext

public class StoreDbContext: DbContext
{
    public StoreDbContext() : base("MyCoupon")
    {
        Database.SetInitializer(new StoreDbInitialier());
    }

    public DbSet<Product> Products { get; set; }
    public DbSet<ProductText> ProductTexts { get; set; }
    public DbSet<ProductImage> Images { get; set; }
    public DbSet<CategoryText> CategoryTexts { get; set; }
    public DbSet<Category> Categories { get; set; }
    public DbSet<Language> Languages { get; set; }
}

这是我的StoreUser班级

public class StoreUser : IdentityUser
{
    public virtual List<Product> Products { get; set; } = new List<Product>();
}

因此用户可以拥有产品

但是当我想添加它们时 与

[Authorize(Roles = "Seller")]
    public IHttpActionResult Post(Product product)
    {
        var userId = HttpContext.Current.User.Identity.GetUserId();
        var userManager = HttpContext.Current.GetOwinContext().GetUserManager<StoreUserManager>();

        var user = userManager.FindById(userId);
        product.Seller = user;
        _db.Products.Add(product);
        _db.SaveChanges();
        return Ok(product);
    }

我收到错误

error

1 个答案:

答案 0 :(得分:0)

您需要致电StoreDbContext班级

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
}