ef-code-first - 首先使用实体​​框架代码在两个实体之间创建 2 个关系

标签 ef-code-first

我正在尝试定义一对多关系,以及相同的 2 个实体“UserProfile”和“Blog”之间的一对一关系。我想我已经成功使用以下代码,但是,它会导致在“Blog”表中创建一个名为“UserProfile_UserId”(FK)的新列。我不明白为什么要这样做。

英文中的关系是: 1.“一个UserProfile有很多博客” 2.“一个 UserProfile 有一个主要的可选(可为空)博客”

所以最终我希望看到从 Blog.UserId 到 UserProfile.UserId 的 FK 以及从 UserProfile.BlogId 到 Blog.Id 的可空 FK 我认为仅此而已……我特别不希望 EF 添加额外的列。

public class UserProfile
{
    [Key]
    public int UserId { get; set; }
    public int? BlogId { get; set; }
    public virtual Blog Blog { get; set; }  // This is a user's main blog
    public virtual ICollection<Blog> AllUsersBlogs { get; set; }
}

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


    public int UserId { get; set; }

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

最佳答案

这是一件非常棘手的事情 - 默认情况下,CF 将所有关系/FK-s 放在一侧。这是有原因的,因为它简化了事情,避免了循环引用和矛盾的两侧的“约束”

what often happens is the error reporting that from one FK ir requires to be of multiplicity '1' and from the other FK it has to be * - resulting in an exception.

但我认为这可以满足您的所有需求 - 您只需要小心地“输入”数据...

public class UserProfile
{
    [Key]
    public int UserId { get; set; }
    [ForeignKey("Blog")]
    public int? BlogId { get; set; }
    public virtual Blog Blog { get; set; }  // This is a user's main blog
    public virtual ICollection<Blog> AllUsersBlogs { get; set; }
}

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

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

    // [ForeignKey("UserId")]
    public virtual UserProfile User { get; set; }
}

在你流畅的配置中......

modelBuilder.Entity<Blog>()
    .HasRequired(x => x.User)
    .WithMany(x => x.AllUsersBlogs)
    .HasForeignKey(x => x.UserId)
    .WillCascadeOnDelete(false);

然后像这样使用它......

var user = db.UserProfiles.Add(new UserProfile
{
    //Blog = mainblog,
    AllUsersBlogs = new List<Blog>
    {
        new Blog{},
        new Blog{},
        new Blog{},
        new Blog{},
        new Blog{},
    }
});
db.SaveChanges();
var mainblog = new Blog { User = user, };
user.Blog = mainblog;
db.SaveChanges();

请注意,对于主博客 - 您现在必须明确指定博客的 用户 - 并将其设置为用户的主博客。

那是因为您现在有两种不同的关系 - 一种是强制性的(博客中的用户)- 另一种是可选的主博客。

Anyhow, if this doesn't satisfy your demands (though it looks it should I think) - then I'd suggest that you let it create things by default and have FK-s on the Blog side, you lose the BlogId but it simplifies things a lot.

关于ef-code-first - 首先使用实体​​框架代码在两个实体之间创建 2 个关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16303275/

相关文章:

entity-framework - 为什么我必须手动提供外键属性值(在这种情况下)?

c# - 如何删除没有子类别的类别

entity-framework - .WithMany() 和 .WithOptional() 的区别?

c# - Entity Framework Code First MySql 复数表

c# - 如何从模式优先模型在不同主机上创建数据库?

c# - 当里面没有 DbSet<> 时如何使用 DbContext 进行查询?

entity-framework - 使用 Entity Framework Code First 更新数据库架构

c# - EF Code First 阻止使用 Fluent API 进行属性映射

c# - Entity Framework 代码优先 - 将两个字段联合到一个集合中

c# - "The * field is required"当EF对象已经有字段