使用以下型号:
public class User {
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("Id")]
public List<UserLog> UserLogs { get; set; }
}
public class UserLog {
[Key]
public long LogId { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public string LogAction { get; set; }
public DateTime LogCreatedOn { get; set; }
public string By { get; set; }
}
我可以使用一个SaveChangesAsync()来插入/更新User和UserLog。
我遇到的问题是当我向UserLog添加条目,然后删除用户,最后调用SaveChangesAsync();从未添加过UserLog。
e.g。
_db.UserLogs.Add(userLogItem); //never gets added.
//await _db.SaveChangesAsync(); //even trying to call this line right after.
_db.Users.Remove(user);
await _db.SaveChangesAsync();
非常感谢任何建议。
答案 0 :(得分:0)
当我有一对多关系时,这是我定义模型的方式。
public class User
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<UserLog> UserLogs { get; set; }
}
public class UserLog
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public long LogId { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public string LogAction { get; set; }
public DateTime LogCreatedOn { get; set; }
public string By { get; set; }
[ForeignKey("Id")]
public virtual User User { get; set; }
}