简体   繁体   English

如何首先使用代码属性设置一对多关系?

[英]How to property set one-to-many relationship with code first?

Entity framework throws an exception when I try and save an object. 当我尝试保存对象时,实体框架会引发异常。 Probably it's because of a many to one relationship and it doesn't know how to insert. 可能是由于多对一的关系,并且不知道如何插入。

Models: 楷模:

public class Photo
{
    public Guid Id {get;set;}
    public List<Tag> Tags {get;set;}
}

public class Tag
{
    public Guid Id {get;set;}
    public string TagText {get;set;}
}

This works fine if i dont try and link two or more Photos to the same tag. 如果我不尝试将两个或多个照片链接到同一标签,则效果很好。

Example: 例:

Photo photo1 = new Photo();
Photo photo2 = new Photo();
Tag tag = new Tag() { TagText = "#EntityFramework"};
photo1.Tags.Add(tag);
photo2.Tags.Add(tag);
_content.SaveChanges(); //Exception 

Anyone know how to set this up correctly with code first? 有人知道如何首先使用代码正确设置此设置吗?


Update: 更新:

Exception: Additional information: Multiplicity constraint violated. 例外:其他信息:违反多重性约束。 The role 'X' of the relationship 'X' has multiplicity 1 or 0..1. 关系“ X”的角色“ X”的多重性为1或0..1。


Update: 更新:

Script generated by add-migration 由add-migration生成的脚本

 CreateTable(
            "dbo.Tags",
            c => new
                {
                    Id = c.Guid(nullable: false, identity: true),
                    TagText = c.String(),
                    Photo_Id = c.Guid(),
                })
            .PrimaryKey(t => t.Id)
            .ForeignKey("dbo.Photos", t => t.Photo_Id)
            .Index(t => t.Photo_Id);

Also define a collection property in Tag for many to many: 还可以在Tag为多对多定义一个集合属性:

public class Tag
{
    ...
    public ICollection<Photo> Photos { get; set; }
}

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

相关问题 迁移一对多关系EF代码优先 - migration one-to-many relationship EF code first aproach 与Code First的单向一对多关系 - Uni-directional one-to-many relationship with Code First EF代码中一对多关系的隐式密钥优先 - Implicit Key for a one-to-many relationship in EF code first 如何使3个实体之间的一对多关系与Entity Framework Core 2.1一起使用 - 代码优先 - How to make one-to-many relationship between 3 entities work with Entity Framework Core 2.1 - code-first 如何首先在实体框架 6 代码中创建可为空的一对多关系 - How to create nullable one-to-many relationship in Entity Framwork 6 code first 如何使用 EF Code First 来声明一对多关系? - How can I use EF Code First to declare a one-to-many relationship? 实体框架代码优先:如何在两个表之间创建一对多和一对一的关系? - Entity Framework Code First: How can I create a One-to-Many AND a One-to-One relationship between two tables? 在EF Code First中,如何设置一对多属性? - In EF Code First, how do I setup an one-to-many property? 使用 MVC 3 Entity Framework Code-First,如何以一对多的关系创建一个新的“多”object? - Using MVC 3 Entity Framework Code-First, how do you create a new “many” object in a one-to-many relationship? 一对多和一对多关系 - One-to-many and one-to-many relationship
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM