【发布时间】:2018-04-21 00:26:53
【问题描述】:
自从向我的 Entity Framework 项目添加日志记录功能后,我一直无法从表中删除任何记录。
这里是添加到数据库的对象的数据类,用户到用户表和日志到日志表:
public class User
{
public string UserName { get; set; }
[Key]
public string ApiKey { get; set; } //unique database key and API key for user
public ICollection<Log> Logs { get; set; }
public User() { }
}
public class Log
{
[Key]
public int logID { get; set; }
public string logString { get; set; }
public string logDateTime { get; set; }
public string userAPIKey { get; set; }
public Log() { }
}
以下是将日志添加到表中的方式,因为自从添加日志以来我一直遇到问题:
public void addLogToUserWithApiKey(string logMessage, string apiKey)
{
Log newLog = new Log();
newLog.logID = makeLogID();
newLog.logString = logMessage;
newLog.logDateTime = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToString("h:mm:ss tt");
newLog.userAPIKey = apiKey;
using (var context = new UserContext())
{
User logUser = checkIfUserExistsWithApiKeyandReturnUser(apiKey);
if (logUser.Logs == null)
{
logUser.Logs = new Collection<Log>();
}
logUser.Logs.Add(newLog);
context.Logs.Add(newLog);
context.SaveChanges();
}
}
最后,这是删除记录的代码:
public void deleteUserFromDatabase(string mApiKey)
{
using (var context = new UserContext())
{
try
{
User userToDelete = checkIfUserExistsWithApiKeyandReturnUser(mApiKey);
if (userToDelete != null)
{
context.Users.Attach(userToDelete);
context.Users.Remove(userToDelete);
context.SaveChanges();
}
}
catch (Exception e) { }
}
}
当 delete 方法是这样时,没有调用异常,但它仍然不起作用。
我把删除方法改成这样了:
User userToDelete = checkIfUserExistsWithApiKeyandReturnUser(mApiKey);
if (userToDelete != null)
{
if (userToDelete.Logs != null)
{
userToDelete.Logs.ToList().ForEach(log => userToDelete.Logs.Remove(log));
}
context.Users.Attach(userToDelete);
context.Users.Remove(userToDelete);
context.SaveChanges();
}
我收到了这个错误信息:
DELETE 语句与 REFERENCE 约束“FK_dbo.Logs_dbo.Users_User_ApiKey”冲突。冲突发生在数据库“SecuroteckWebApplication.Models.UserContext”、表“dbo.Logs”、列“userAPIKey”中。该语句已终止。
【问题讨论】:
-
@Kell 它似乎没有意识到这一点
标签: c# entity-framework