简体   繁体   English

对同一实体的外键引用

[英]Foreign-Key References to the Same Entity

I have the below model: 我有以下模型:

class Client
{        
    [Key]
    public int Id { get; set; }
    public string Nom { get; set; }
    public string Prenom { get; set; }         
    public Nullable<DateTime> date_naissance { get; set; }
    public Sex? Sexe { get; set; }
    public Client Parent { get; set; }
}

I used code first to generate my table. 我首先使用代码来生成表。 When I tried to save the records using the code below, I wasn't able to determine how to populate the Parent field. 当我尝试使用下面的代码保存记录时,我无法确定如何填充“ Parent字段”。 A Client can be a parent of other Client s. 一个Client可以是其他Client的父母。

Client client = new Client();

client.Id = int.Parse(item.ID);
client.Nom = item.Nom;
client.Prenom = item.Prenom;
client.date_naissance = DateTime.Parse(item.DateNaissance);
client.Sexe = (Sex)Enum.Parse(typeof(Sex), item.Sexe);

int parent;
bool par = int.TryParse(item.Parent, out parent);

// this does not work:                       
if (par)
    client.Parent.Id = parent;

db.clients.Add(client);
db.SaveChanges();

If the parent Client instance is not already created, you will need to create a new one. 如果尚未创建父Client实例,则需要创建一个新实例。 You can always create a new Client instance and assign it the parent's Id, but the instance assigned will lack all of the other information about the parent. 您始终可以创建一个新的Client实例,并为其分配父级ID,但是分配的实例将缺少有关父级的所有其他信息。 An example of this is below. 下面是一个示例。

client.Parent = new Client() { Id = parentId };

Ideally, you will look up the parent from the context and assign it to the client: 理想情况下,您将从上下文中查找父级并将其分配给客户端:

var parent = context.Clients.Find(parentId);
if (parent != null)
{
    client.Parent = parent;
}
else
{
    // Handle an invalid ID
}

Additionally, I would suggest changing the Parent property to a virtual property: 另外,我建议将Parent属性更改为虚拟属性:

public virtual Client Parent { get; set; }

This will allow you to take advantage of two useful features of the Entity Framework: lazy loading and automatic change tracking. 这将使您能够利用实体框架的两个有用功能:延迟加载和自动更改跟踪。 Entities or collections of entities referenced by navigation properties specified with the virtual keyword will only be loaded the first time they are used. virtual关键字指定的导航属性引用的实体的实体或集合仅在首次使用时才会加载。 With the virtual keyword, accessing the Parent property the first time will load the Parent entity for that Client and return it. 使用virtual关键字,第一次访问Parent属性将为该Client加载Parent实体并返回它。 Without the virtual keyword, the Parent property will return null unless you explicitly load and assign a value to it. 没有virtual关键字,除非您显式加载并为其分配值,否则Parent属性将返回null

您可能不希望将整个Client结构作为父级传递,您可能只传递整数ID来引用父级。

Try making the navigation properties (ie Parent) virtual and don't forget to initialize them. 尝试将导航属性(即“父级”)设为虚拟,不要忘记对其进行初始化。 So first you have to change your class property to: 因此,首先您必须将class属性更改为:

public virtual Client Parent { get; set; }

and then in the code: 然后在代码中:

client.Parent = new Parent();
client.Parent.Id = parentId;

you must create an instance of the parent. 您必须创建父对象的实例。 or you can't set it. 或您无法设置它。

class Client
{                
    public int Id { get; set; }

    public Client Parent { get; set; }

    /// <summary>
    /// Initializes a new instance of the <see cref="Client"/> class.
    /// 
    /// WITH PARENT
    /// </summary>
    /// <param name="id">The identifier.</param>
    /// <param name="parent">The parent.</param>
    public Client(int id, Client parent)
    {
        this.Id = id;
        this.Parent = parent;                    
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="Client"/> class.
    /// 
    /// WITHOUT PARENT
    /// </summary>
    /// <param name="id">The identifier.</param>
    public Client(int id)
    {
        this.Id = id;
    }
}

public static void Main(string[] args)
{
        Client client = new Client(1);

        Client clientWithParent = new Client(2, client);

        Console.Write("parent id :" + clientWithParent.Parent.Id);
}

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

相关问题 在Entity Framework上创建外键关系的问题 - Problems creating a Foreign-Key relationship on Entity Framework 实体框架 OneToMany 更新项目 - 缺少外键值 - Entity Framework OneToMany updating items - Missing foreign-key value 外键属性错误 - Foreign-key properties error Mvc,外键关系 - Mvc, Foreign-Key Relationship (Fluent) nHibernate:“与引用一样,外键默认为 Author_id,您可以覆盖它 - (Fluent) nHibernate: "As with References, the foreign-key defaults to Author_id, and you can override it 实体框架外键引用没有映射 - Entity Framework foreign key references not mapping EF添加实体:由于一个或多个外键属性不可为空,因此无法更改关系 - EF adding entity: The relationship could not be changed because one or more of the foreign-key properties is non-nullable 实体框架5无法更改该关系,因为一个或多个外键属性不可为空 - Entity Framework 5 The relationship could not be changed because one or more of the foreign-key properties is non-nullable 实体框架:一个或多个外键属性不可为空 - Entity Framework: one or more of the foreign-key properties is non-nullable 实体框架无法更改关系,因为一个或多个外键属性不可为空 - Entity Framework The relationship could not be changed because one or more of the foreign-key properties is non-nullable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM