简体   繁体   English

.NET Entity Framework Core 2.0 - 代码优先 - 意外的表关系结果

[英].NET Entity Framework Core 2.0 - Code-First - Unexpected Table Ralationship Result

I'm learning EF Core and put wrong code in the Fluent API, which resolved to very strange One-to-One Relationship in the created database.我正在学习 EF Core 并在 Fluent API 中放置了错误的代码,这在创建的数据库中解析为非常奇怪的一对一关系。 Let me give you some code and more specific information and I really hope someone can explain how this happen.让我给你一些代码和更具体的信息,我真的希望有人能解释这是怎么发生的。

I have coded 3 Models in C# and 1 Mapping table.我在 C# 中编写了 3 个模型和 1 个映射表。 The problem occurred between 2 of the models.问题发生在 2 个模型之间。

public class Album
{
    [Key]
    public int AlbumId { get; set; }

    public string BackgroundColor { get; set; }

    public Boolean IsPublic { get; set; }

    public int PhotographerId { get; set; }

    public Photographer Photographer { get; set; }

    public IList<PictureAlbum> AlbumPictures { get; set; } = new List<PictureAlbum>();
}

public class Photographer
{
    [Key]
    public int PhotographerId { get; set; }

    [Required]
    public string Username { get; set; }

    [Required]
    [MinLength(6)]
    public string Password { get; set; }

    [Required]
    public string Email { get; set; }

    [Required]
    public DateTime RegisteredDate { get; set; }

    [Required]
    public DateTime BirthDate { get; set; }

    public IList<Album> Albums { get; set; } = new List<Album>();
}

So everything looks right.所以一切看起来都不错。 'Album' have Photographer and Foreign Key. “相册”有摄影师和外键。 Photographer have Collection of 'Albums'.摄影师收藏了“相册”。

Here is part of the table relationship in the Fluent API (included only the relationship for the "strange" relationship between Album and Photographer):以下是 Fluent API 中的部分表关系(仅包括相册和摄影师之间“奇怪”关系的关系):

builder.Entity<Album>()
            .HasOne(p => p.Photographer)
            .WithMany(a => a.Albums)
            .HasForeignKey(p => p.AlbumId);

As you can see, instead of putting "PhotographerId" for the ForeignKey, I put "AlbumId" which should leads to "Self-Referencing" Table, right?如您所见,我没有将“PhotographerId”作为外键,而是将“AlbumId”放入“自引用”表中,对吗?

But this looks not true, because when I review the Diagram of the Database I see the following:但这看起来不正确,因为当我查看数据库图时,我看到以下内容:

Diagram (Relation between Album and Photographer)图(相册与摄影师的关系)

More of that, if you look in the Key's they have, they looks like they are coded in C#:更重要的是,如果您查看它们拥有的密钥,它们看起来像是用 C# 编码的:

Tables Keys表键

Now I do not understand how this is possible.现在我不明白这怎么可能。 I created the Database using Migrations.我使用迁移创建了数据库。

  1. I did not put the right Foreign Key in FluentApi, but the Diagram shows One-to-One Relationship?我没有在 FluentApi 中放置正确的外键,但图中显示了一对一的关系?
  2. In the Keys of the table, we can see that they don't have Relationship.在表的键中,我们可以看到它们没有关系。
  3. More than that I have IList Albums in "Photographer" Model, which by my understanding should lead to may be something different, but not One-to-One.更重要的是,我在“摄影师”模型中有 IList 相册,据我所知,这应该会导致不同的东西,但不是一对一。

I know I made a mistake with the FluentApi, but I want to learn from my mistake and to understand how this result happened.我知道我在 FluentApi 上犯了一个错误,但我想从我的错误中吸取教训并了解这个结果是如何发生的。

This is my first post here and I hope I can get some support/help.这是我在这里的第一篇文章,我希望我能得到一些支持/帮助。

Thank you.谢谢你。

It's a weird situation.这是一个奇怪的情况。 You effectively configured a one-to-one association between Photographer (principal) and Album (dependent).您有效地配置了Photographer (主要)和Album (从属)之间的一对一关联。 How this happened becomes clear by using the correct range variables ( p and a ) in the mapping:通过在映射中使用正确的范围变量( pa ),这是如何发生的变得很清楚:

builder.Entity<Album>()
        .HasOne(a => a.Photographer)
        .WithMany(p => p.Albums)
        .HasForeignKey(a => a.AlbumId); // i.e. this is Album.AlbumId

Album.AlbumId now is Album s primary key and its foreign key to Photographer . Album.AlbumId现在是Album的主键它对Photographer外键。 The primary key is not an identity field, because it "borrows" its value from the owning Photographer .主键是没有标识字段,因为它“借用”从拥有它的价值Photographer This is a common way of modeling 1:1 associations in a relational database.这是在关系数据库中对 1:1 关联进行建模的常用方法。 But for EF, the association is 1-n and it's a bit surprising that it doesn't give a warning about this anomaly.但是对于 EF,关联是 1-n 并且它没有给出有关此异常的警告有点令人惊讶。

The funny thing is that is still works.有趣的是它仍然有效。 You can establish the 1:1 association between a Photographer and an Album by adding the album to Photographer.Albums , and EF saves everything alright.您可以通过将Album添加到Photographer.Albums来建立PhotographerAlbum之间的 1:1 关联,EF 保存一切正常。 However, if you try to add a second Album , EF will run into a duplicate primary key exception.但是,如果您尝试添加第二个Album ,EF 将遇到重复的主键异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架核心multipleDbContext代码优先迁移共享实体 - Entity framework core multipleDbContext code-first migration of shared entity Entity Framework Core 2.1,使用代码优先迁移重命名表而不删除和创建新表 - Entity Framework Core 2.1, rename table using code-first migrations without dropping and creating new table 在SQLite中为实体框架核心代码优先设置日记模式 - Setting journal mode in SQLite for Entity Framework Core code-first Entity Framework Core 2.2.3不使用代码优先方法创建表与2017年相比 - Entity Framework Core 2.2.3 not creating table using code-first approach vs 2017 连接表中的实体框架核心代码优先多对多属性 - Entity Framework Core code-first many-to-many properties in join table 代码优先实体框架核心中的一对多一对一 - One to Many with One Main in Code-First Entity Framework Core Entity Framework Core错误中的代码优先迁移 - Code-first migration in Entity Framework Core error Entity Framework Core 添加唯一约束代码优先 - Entity Framework Core add unique constraint code-first .NET Entity Framework 代码优先:未加载导航属性 - .NET Entity Framework code-first: navigation properties are not loaded 实体框架代码优先的多对多表外键 - Entity Framework code-first foreign key to many to many table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM