我正在使用 ASP.NET MVC 4 和 Entity Framework 5。我使用模型优先方法来生成数据库。在我的应用程序中,我有一个运行日志表和一个鞋子表。用户可以拥有与跑步日志条目相关联的 0 或 1 双鞋。所以这似乎是一个 0..1 对多的关系,这就是我在模型中设置它的方式。当我context.SaveChanges()
添加一个没有任何关联鞋子的新条目时,我收到此错误:
The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_ShoeLogEntry\".
一旦我为日志条目选择一双鞋,它就可以正常工作。那么如何正确设置关系,以便日志条目可以为鞋子提供空值?我在这里粘贴了下面的代码:
我用来添加新条目的代码
le.ActivityType = ctx.ActivityTypes.Find(le.ActivityTypesId);
le.User = ctx.Users.Find(le.UserUserId);
le.Shoe = ctx.Shoes.Find(le.ShoeShoeId); //ShoeShoeId is null if nothing picked
ctx.LogEntries.Add(le);
ctx.SaveChanges();
我曾尝试检查ctx.Shoes.Find(le.ShoeShoeId)
返回 null 和设置le.Shoe
tonull
和le.ShoeShoeId
to null
,-1
但没有奏效。
我试图在下面粘贴相关代码,但这对我来说很新。所以如果有必要我可以添加更多。我真的很感激任何帮助!
外键设置
-- Creating foreign key on [ShoeShoeId] in table 'LogEntries'
ALTER TABLE [dbo].[LogEntries]
ADD CONSTRAINT [FK_ShoeLogEntry]
FOREIGN KEY ([ShoeShoeId])
REFERENCES [dbo].[Shoes]
([ShoeId])
ON DELETE NO ACTION ON UPDATE NO ACTION;
-- Creating non-clustered index for FOREIGN KEY 'FK_ShoeLogEntry'
CREATE INDEX [IX_FK_ShoeLogEntry]
ON [dbo].[LogEntries]
([ShoeShoeId]);
GO
主键设置
-- Creating primary key on [ShoeId] in table 'Shoes'
ALTER TABLE [dbo].[Shoes]
ADD CONSTRAINT [PK_Shoes]
PRIMARY KEY CLUSTERED ([ShoeId] ASC);
GO
-- Creating primary key on [LogId] in table 'LogEntries'
ALTER TABLE [dbo].[LogEntries]
ADD CONSTRAINT [PK_LogEntries]
PRIMARY KEY CLUSTERED ([LogId] ASC);
GO
模型生成的日志条目类
public partial class LogEntry
{
public int LogId { get; set; }
public string ActivityName { get; set; }
public System.DateTime StartTime { get; set; }
public string TimeZone { get; set; }
public int Duration { get; set; }
public decimal Distance { get; set; }
public Nullable<int> Calories { get; set; }
public string Description { get; set; }
public string Tags { get; set; }
public int UserUserId { get; set; }
public Nullable<int> ShoeShoeId { get; set; }
public int ActivityTypesId { get; set; }
public virtual User User { get; set; }
public virtual Shoe Shoe { get; set; }
public virtual ActivityTypes ActivityType { get; set; }
}
模型生成的鞋类
public partial class Shoe
{
public Shoe()
{
this.ShoeDistance = 0m;
this.LogEntries = new HashSet<LogEntry>();
}
public int ShoeId { get; set; }
public string ShoeName { get; set; }
public decimal ShoeDistance { get; set; }
public int ShoeUserId { get; set; }
public string ShoeBrand { get; set; }
public string ShoeModel { get; set; }
public System.DateTime PurchaseDate { get; set; }
public int UserUserId { get; set; }
public virtual User User { get; set; }
public virtual ICollection<LogEntry> LogEntries { get; set; }
}