.NET MVC循环引用问题,实体
我知道其他人张贴了关于这一点,但我无法找到这似乎符合我的问题是什么的答案。虽然我是超级新的.NET所以我可能只是不明白的东西。
I know others have posted about this, but I can't find an answer that seems to match what my question is. Although I am super new to .net so I may just not understand something.
我的网站有一个项目对象,这是由一个特定的用户所拥有。该项目有另一种模式用于额外的信息,其他用户可以添加。
My site has a project object, which is owned by a particular user. The project has another model for extra info that other users can add.
我的模型是这样的:
项目
- 在项目业主FK
- 其他的东西
信息
- 项目FK
- 在信息所有者FK
- 其他的东西
不过,我得到错误的引用关系将导致这是不允许的周期性引用。
But I am getting error The referential relationship will result in a cyclical reference that is not allowed.
我认为这是冷门,我有一个FK这两个项目和信息的用户。但用户是不同的,所以我不能干掉一个。有没有办法告诉它?
I think it is upset that I have a fk to a user in both project and info. But the users are different, so I can't get rid of one. Is there a way to tell it that?
此外,我是全新的。NET,所以我希望这不是一个愚蠢的问题。我来自一个Django的背景下,如果与解释帮助。
Again, I am brand new to .net, so I'm hoping this isn't a silly question. I come from a django background, if that helps with explanation.
code:
public class Information
{
[HiddenInput(DisplayValue = false)]
public int InfoID { get; set; }
//user
public virtual User User { get; set; }
[Required(ErrorMessage = "This field is required.")]
public int UserID { get; set; }
//project
public virtual Project Project { get; set; }
[Required(ErrorMessage = "This field is required.")]
public int ProjectID { get; set; }
}
public class Project
{
[HiddenInput(DisplayValue = false)]
public int ProjectID { get; set; }
//user
public virtual User User { get; set; }
[Required(ErrorMessage = "This field is required.")]
public int UserID { get; set; }
}
予除去所有其它的非关系字段,这是因为它们并不重要。
I removed all of the other non-relational fields, since those are not important.
用户名
需要两个实体和 ProjectID
需要信息
实体。这将创建多个级联路径,如果你删除用户
。 用户
- > 信息
和用户
- > 项目
- > 信息
UserID
is required for both entities and ProjectID
is required for Information
entity. This will create multiple cascading paths if you remove a User
. User
-> Information
and User
-> Project
-> Information
.
您必须使用流利的API映射关系,并指定用于至少一个关系,即 WillCascadeOnDelete(假)
You have to map the relationships using Fluent API and specify for atleast one relationship that WillCascadeOnDelete(false)
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany(u => u.Informations)
.HasRequired(i => i.User)
.HasForeignKey(i => i.UserID)
.WillCascadeOnDelete(false);
}
}