- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在学习 Entity Framework 核心,将其与 SQLITE 一起使用我在数据库中有 2 个表。
消息:
CREATE TABLE `Messages` (
`Id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
`IsDeleted` INTEGER NOT NULL,
`FromUserId` INTEGER,
`ToUserId` INTEGER,
`SendDate` TEXT NOT NULL,
`ReadDate` TEXT NOT NULL,
`MessageContent` TEXT,
CONSTRAINT `FK_Messages_Users_ToUserId` FOREIGN KEY(`ToUserId`) REFERENCES `Users`(`Id`) ON DELETE RESTRICT,
CONSTRAINT `FK_Messages_Users_FromUserId` FOREIGN KEY(`FromUserId`) REFERENCES `Users`(`Id`) ON DELETE RESTRICT
);
和用户表:
CREATE TABLE `Users` (
`Id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
`IsDeleted` INTEGER NOT NULL,
`Name` TEXT,
`DisplayName` TEXT,
`Gender` INTEGER NOT NULL,
`BirthDate` TEXT NOT NULL
);
我的 C# 类看起来像:
public class User
{
public int Id {get;set;}
public bool IsDeleted{get;set;}
[Required]
public string Name{get;set;}
public string DisplayName{get;set;}
[Required]
public char Gender{get;set;}
[Required]
public DateTime BirthDate{get;set;}
public User(string n, string dn, char g, DateTime bd)
{
Name=n; DisplayName = dn; Gender = g; BirthDate = bd;
}
protected User(){}
public override string ToString()
{
return string.Format("{0} ({1}) {2}", this.Name, this.Gender,this.BirthDate.ToShortDateString());
}
}
和消息类:
public class Message
{
public int Id{get;set;}
public bool IsDeleted{get;set;}
[Required]
public Users.User FromUser{get;set;}
[Required]
public Users.User ToUser{get;set;}
[Required]
public DateTime SendDate{get;set;}
public DateTime? ReadDate{get;set;}
[Required]
public string MessageContent{get;set;}
protected Message(){}
public Message(User from, User to, string content)
{
this.FromUser = from;
this.ToUser = to;
this.MessageContent = content;
this.SendDate = DateTime.Now;
this.ReadDate = DateTime.Now;
}
}
用户表有效,但是当我尝试通过此向消息添加新实体时:
public override int Insert(Message entity)
{
dbc.Messages.Add(entity);
dbc.SaveChanges();
return entity.Id;
}
我收到以下错误:
SQLite Error 19: 'UNIQUE constraint failed
我不知道哪里出了问题。当我手动将数据插入数据库(使用 sqlite 的数据库浏览器)时,它起作用了。类(class)关系还好吗?
我的 dbContextSnapshot
是:
[DbContext(typeof(RandevouDbContext))]
partial class RandevouDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "2.1.4-rtm-31024");
modelBuilder.Entity("RandevouData.Messages.Message", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("FromUserId");
b.Property<bool>("IsDeleted");
b.Property<string>("MessageContent")
.IsRequired();
b.Property<DateTime?>("ReadDate");
b.Property<DateTime>("SendDate");
b.Property<int>("ToUserId");
b.HasKey("Id");
b.HasIndex("FromUserId");
b.HasIndex("ToUserId");
b.ToTable("Messages");
});
modelBuilder.Entity("RandevouData.Users.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("BirthDate");
b.Property<string>("DisplayName");
b.Property<char>("Gender");
b.Property<bool>("IsDeleted");
b.Property<string>("Name")
.IsRequired();
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("RandevouData.Messages.Message", b =>
{
b.HasOne("RandevouData.Users.User", "FromUser")
.WithMany()
.HasForeignKey("FromUserId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("RandevouData.Users.User", "ToUser")
.WithMany()
.HasForeignKey("ToUserId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
顺便说一下。我无法从两侧配置映射。
Message 实体有 UserFrom 和 UserTo 字段,但是用户实体不能有消息,因为一次他是“userFrom”而另一次他可以是“userTo”。
还有一个代码,我在其中创建消息实体
public int SendMessage(int senderId, int receiverId, string content)
{
var dao = new MessagesDao();
var usersDao = new UsersDao();
var userService = new UserService(mapper);
var sender = usersDao.Get(senderId);
var receiver = usersDao.Get(receiverId);
var entity = new Message(sender,receiver,content);
var id = dao.Insert(entity);
return id;
}
我覆盖 GET 方法的用户 dao
public override User Get(int id)
{
using (var context = new RandevouDbContext())
{
var user = dbc.Find<User>(id);
return user;
}
}
和我重写 Add 方法的 MessagesDao
public override int Insert(Message entity)
{
using (var dc = new RandevouDbContext())
{
dc.Messages.Add(entity);
dc.SaveChanges();
return entity.Id;
}
}
最佳答案
要修复“UNIQUE”约束异常,您需要确保您正在使用的所有实体都被您要保存到的上下文跟踪。
例如
// Get user from one context
User thisUser = db.Users.Find(3);
//Now imagine you have another context which has been created later on
DbContext newContext = new DbContext();
//and you want to create a message, assign it to your user
//and save it to the new context
Message newMessage = new Message
{
Text = "Hello",
User = thisUser
}
newContext.Messages.Add(newMessage);
// saving this to newContext will fail because newContext is not tracking thisUser,
// Therefore attach it...
newContext.Users.Attach(thisUser).
//now newContext is tracking thisUser *AND* newMessage, so the save operation will work
newContext.SaveChanges();
关于c# - EF Core SQLITE - SQLite 错误 19 : 'UNIQUE constraint failed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52718652/
EF POCO 和 EF Code First 有什么区别? 如果我一开始只使用 POCO,我可以将 EF 与它们一起使用吗? 最佳答案 如果您首先使用 EF 代码,您将拥有 POCO 对象,并且数据
EF POCO 和 EF Code First 有什么区别? 如果我一开始只使用 POCO,我可以将 EF 与它们一起使用吗? 最佳答案 如果您首先使用 EF 代码,您将拥有 POCO 对象,并且数据
我有一个基于 .NET 4.8 和 EF 6.4.4 的项目。我们正在逐步迁移到 .Net Core,但在此过程中我可以创建一个 .NET Core 数据上下文类 EF Core 并将两者指向相同的实
我有以下 Entity Framework 5 代码第一类 public class Airplane { public int Id { get; set; } public int
我正在尝试使用 Entity Framework Core 对现有数据库进行逆向工程.我试着按照指示from Microsoft但我遇到了错误: Unable to find provider ass
当数据库不是由 EF 代码首先创建时,有没有办法检查 DbContext 是否与数据库匹配? 我正在寻找与 Database.CompatibleWithModel 类似的功能但没有元数据。 最佳答案
目前,我正在重构我的上下文方法的测试,以不再需要真正的数据库。我使用 Ef Core。 所以我通读了 Microsoft 文档如何测试上下文方法。我首先找到了 EF6 测试的文档,然后阅读了 EfCo
我正在使用 EF 6 Database.SqlQuery 语句来执行存储过程,并实现错误和事务处理,打开和关闭事务(处理多个记录,如果一个记录有错误,仅回滚此,并提交其他任何内容无错误完成)。 Lis
我首先使用 EF 数据库,因为我喜欢在 SQL Management Studio 中设计我的数据库,坦率地说,让 Visual Studio 直接从数据库创建所有实体非常容易,而无需执行任何代码。
我的项目中有几个迁移文件,由于我对上次迁移进行了手动修改,所以我不想使用“程序包管理器控制台”重新生成它。我只需要添加 1 列。所以在之前的迁移中手动添加了这个(我可以这样做,因为还没有人升级过)。
原文:https://bit.ly/2umidlb 作者:jon p smith 翻译:王亮 声明:我翻译技术文章不是逐句翻译的,而是根据我自己的理解来表述的。其中可能会去除一些本人实在不知道如何组
我们想开始一个新项目,我们决定从一开始就在一些表中使用 Columnstore 索引和聚簇索引,我们如何使用 Code First EF Core 3.1 做到这一点? 最佳答案 您应该将主键更改为非
我在 Entity Framework 6.0 上。这是一个开发问题,而不是生产问题。 我想我有一个相互矛盾的策略。 目前,我设置了 DropCreateDatabaseIfModelChanges
我在 VS 2012 RTM 上,使用 EF 5。我在做代码优先,但由于我只是在开发中,所以试图忽略代码迁移。为了避免它们,我有这一套 Database.SetInitializer(new Drop
我有复杂的审计字段类型 我的复杂类型: [ComplexType] public class AuditData { [Column("CreatorUserId")] public
我已经阅读了很多关于如何在关系中指定外键名称的帖子,没有遇到任何问题。不过,我想知道的是,有没有办法更改主键和关系的命名方式? 例如,您有一个以 UserId 作为主键的 User 表。 EF 代码第
我刚刚安装了新的Entity Framework 4.1 NuGet包,因此根据NuGet指令和this article of Scott Hanselman替换了EFCodeFirst包。 现在,想
我的应用程序基于 .NET 4.0 和 EF 4。我现在正在考虑升级到最新版本。 是否有任何可能对我的申请产生不利影响的重大变化或行为差异? 升级路径有多简单?升级到 EF 5 是否需要任何代码更改或
假设您必须使用 EF Code First 和 POCO 类开发支持多种语言的网站,您将如何对 POCO 类进行建模以支持这种情况? 通过多语言支持,我的意思不仅是拥有例如在一些资源文件中为您的 UI
我首先使用 EF 4.1 代码。鉴于以下类片段: public class Doctor { public virtual ICollection Hospitals { get; set;
我是一名优秀的程序员,十分优秀!