gpt4 book ai didi

c# - 我如何在我的 child 中设置对 ForeignKey 的依赖

转载 作者:太空宇宙 更新时间:2023-11-03 13:41:15 25 4
gpt4 key购买 nike

我需要这个 ID 来从我的 parent 那里获取数据集合。计划是使用 ParentId 从存储库中获取所有 friend 。

为了说明,我有一个父类和子类,每个类还有一个映射器。我想我必须在 ParentMapper 中定义键。

查看我代码中的注释

    {
public class Child {
public int IdChild { get; set; }
public string ChildName {get;set;}
// here is the problem
//I need to define ParentID as ForeignKey in some way but how??
//I belive its done in the ParentMapper
public virtual int ParentId { get; set; } //ForeignKey

public virtual ICollection<Friend> Friends { get; set; }

//The plan is to fetch all friends from the repository by using the ParentId and
//keep the entity as clean as possible.
public virtual ICollection<Friend> FamilyFriends { get; set; }
}
public class Parent {
public int IdParent { get; set; }
public string ParentName {get;set;}

public virtual ICollection<Friend> Friends { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
}


{
class ParentMapper : EntityTypeConfiguration<Parent>
{
public ParentMapper()
{
HasKey(one => one.IdParent);

//I started out like this but its not possible....
//But this will give an error obviusly
HasMany(c => c.Children).WithRequired(d => d.ParentId).HasForeignKey(one => one.ParentId);
}
}
}

{
class ChildMapper : EntityTypeConfiguration<Child>
{
public ChildMapper()
{
HasKey(one => one.IdChild);
}
}
}

最佳答案

public class Child {

public int ChildId { get; set; }

public string ChildName {get;set;}

[ForeignKey("Parent")]
public int ParentId { get; set; } //ForeignKey
public Parent Parent{get; set;}


public List<Friend> Friends { get; set; }

public List<Friend> FamilyFriends { get; set; }
}
public class Parent {
public int ParentId { get; set; }
public string ParentName {get;set;}

public List<Friend> Friends { get; set; }
public List<Child> Children { get; set; }
}

public class Friend
{
public int FriendId { get; set; }
public string FriendName {get;set;}

[ForeignKey("Parent")]
public int ParentId{get;set;}
public Friend Parent {get;set;}

[ForeignKey("Child")]
public int ChildId{get;set;}

[InverseProperty("Friends")]
public Child Child {get;set;}

[ForeignKey("ChildFam")]
public int ChildFamId{get;set;}

[InverseProperty("FamilyFriends")]
public Child ChildFam {get;set;}
}

关于c# - 我如何在我的 child 中设置对 ForeignKey 的依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16912207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com