gpt4 book ai didi

c# - EF 不包括外键使用外类型的最后一个对象

转载 作者:太空宇宙 更新时间:2023-11-03 13:18:28 26 4
gpt4 key购买 nike

EF 6,VS 2013,本地数据库。

我有一个非常基本的 Entity Framework 测试项目。它有 UsersBlogs

每个用户可以有多个博客,一个博客有一个与用户相关的外键。

我创建了一个 User 和一个博客,但我没有将它们连接起来。 EF 在没有我指示的情况下建立了连接。

如果我不创建 User 对象,它就会按照我的意愿出现错误。 IE。不要保存缺少必填字段的对象。

public class FieldSizes
{
public const int Names = 32;
public const int Long = 80;
}

class Program
{
static void Main(string[] args)
{
using(Dbf db = new Dbf())
{
var user = db.Users.Create();
user.PasswordHash = "tests";
user.UserName = "sssss";
db.Users.Add(user);

var blog = db.Blogs.Create();
blog.Title = "gssss";
blog.ContentId = 42;
db.Blogs.Add(blog);
db.SaveChanges();
}
}
}

public class Dbf : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Blog> Blogs { get; set; }
}

public class User
{
[Key]
public int Id { get; set; }

[MaxLength(FieldSizes.Names)]
public string UserName { get; set; }

public string PasswordHash { get; set; }

public void SetPassword(string password)
{
this.PasswordHash = "[Encryption Key]";
}

public virtual List<Blog> Blogs { get; set; }
}

public class Blog
{
[Key]
public int Id { get; set; }

[ForeignKey("User")]
public int UserId { get; set; }

public virtual User User { get; set; }

[MaxLength(FieldSizes.Long)]
public string Title { get; set; }

public int ContentId { get; set; }
}

这是在 EF 中设计的吗?我的代码有错误吗?我不明白为什么 EF 这样做。

最佳答案

是的,这是设计使然,但如果我们不了解它,就会成为问题。

当您创建一个新的 User 时,EF 将分配一个临时键作为主键。新创建的 User 将具有临时 Id = 0,因为它是整数的默认值。 key 是临时 key ,如果是身份 key ,保存后会更新。

更多:EntityKey.IsTemporary .

而当你新建一个Blog时,UserId的默认值也是0。这会导致Blog用户在数据库中有关系。

您也可以手动分配临时 key 来建立关系。

user.Id = 1234;
blog.UserId = 1234;

这是一个 great article解释这个案例。这是摘录的一部分。

When creating a new relation we just need a dependent entity and a primary key of a parent entity. The tricky part here is that primary key must be unique for all attached entities of a given type. Even if we use auto generated keys in the database we must still assign temporary unique key to newly created entities which are added to relations.

关于c# - EF 不包括外键使用外类型的最后一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25191606/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com