[英]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.