Cb-DbSet.Add()不起作用
作者:互联网
我有这样的课:
[Table("member_activation")]
public partial class MemberActivation
{
[Key]
public Int64 member_id { get; set; }
public String token { get; set; }
}
我的数据库:
public class SMADbContext : DbContext
{
public SMADbContext() : base("SMADB")
{
Database.SetInitializer<SMADbContext>(new NullDatabaseInitializer<SMADbContext>());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
public DbSet<Member> Members { get; set; }
public DbSet<MemberActivation> MemberActivations { get; set; }
public DbSet<ApiAccount> ApiAccounts { get; set; }
public DbSet<ApiHardware> ApiHardwares { get; set; }
public DbSet<MemberRelation> MemberRelations { get; set; }
}
在我的控制器中:
[Route("tester")]
[AllowAnonymous]
public IHttpActionResult tester()
{
using (var db = new SMADbContext())
{
var memberActivation = new MemberActivation();
memberActivation.member_id = 10155;
memberActivation.token = "hello";
db.MemberActivations.Add(memberActivation);
return Json(new { dbset = db.MemberActivations.ToList(), memberAct = memberActivation });
}
}
db.MemberActivations.Add(memberActivation);不起作用.当我返回json时,dbset不包括新创建的memberActivation.我没有db.SaveChanges(),因为在将memberActivation推送到dbset之前它不会保存
解决方法:
您不能设置member_id,它是密钥,并且ef将其用作标识.它将被忽略.您可以配置ef,以便member_id不是身份,但这是另一个主题.
db.MembershipActivations.Add( new MemberActivation { token = "hello"}):
db.SaveChanges();
应该工作正常.
但是,如果出现的话,则您有一个现有成员,并且您正在尝试通过连接表设置与该实体的关系.然后,您应该检索该实体并设置memberactivation. Ef将为您解决其余的问题.有点猜测,因为我需要查看所涉及的实体.
标签:dbset,asp-net,c 来源: https://codeday.me/bug/20191029/1959130.html