如何获得最后插入id从mysql与实体框架

本文关键字:mysql 实体 框架 id 何获得 最后 插入 | 更新日期: 2023-09-27 18:02:37

var forSentTable = new mailsent { Subject = Subject.Text, Mailbody = editor1.InnerText, SentTime = DateTime.Now, SentBy = mailFromEmail };
// var forSentTableBody = new MailSent { };
context.mailsents.Add(forSentTable);
//context.MailSents.Add(forSentTableBody);
context.SaveChanges();
//tried this one but not working with mysql(but it works with sql server)
var mailID = forSentTable.MailID;

如何获得最后插入id从mysql与实体框架

如果您使用数据库优先模型。您必须将Identity设置为模型的StoreGeneratedPattern属性的值。如果您使用代码优先模型。试试这个

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
 public Guid ID { get; set; }