简体   繁体   English

如何在实体框架中将一个实体映射到许多实体?

[英]How do I map one entity to many entities in Entity Framework?

I have 4 entities. 我有4个实体。 They look something like this: 他们看起来像这样:

public abstract class Entity
{
    public Guid Id { get; set; }
    public DateTime CreationDate { get; set; }
}

public class Client :
    Entity
{
    public string Name { get; set; }
    // ...
    public IList<Note> Notes { get; set; }
}

public class Supplier :
    Entity
{
    public string Name { get; set; }
    // ...
    public IList<Note> Notes { get; set; }
}

public class Note :
    Entity
{
    public Guid EntityId { get; set; } // This points to the Id field of a Client or Supplier
    public virtual Entity Entity { get; set; }
    public string EntityName { get; set; } // "Client", "Supplier", etc.
}

Now, what I want is for this to create 3 tables, Client, Supplier, and Note. 现在,我要为此创建3个表,即Client,Supplier和Note。 The note table needs to point to the client and supplier note on the EntityId field. 注释表需要指向EntityId字段上的客户和供应商注释。 What is actually happening, is that EF is adding Client_ID and Supplier_ID fields to the Note table, with foreign keys to each respective table. 实际发生的情况是,EF将“ Client_ID”和“ Supplier_ID”字段添加到“注释”表中,并对每个表添加了外键。 The effect of this is basically that notes can only be created if both client and supplier are included. 基本上,这样做的效果是,只有同时包含客户和供应商,才能创建便笺。

What do I need to do to make this behave the way I need? 我需要怎么做才能使其表现出所需的方式?

Try this Info 试试这个信息

this.HasOptional(t => t.Client)
                .WithMany(t => t.Notes )
                .HasForeignKey(d => d.Id);

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

相关问题 如何与实体框架建立一对多关系? - How do I represent a one to many relationship with the Entity Framework? 如何在实体框架核心中映射一对多的可选递归关系 - how to map one to many optional recursive relationship in Entity Framework core 如何使用实体框架和Fluent API映射复杂的一对多 - How to map complex one-to-many with Entity Framework and Fluent API 映射一个到多个复合密钥实体框架5 - Map one to many composite key Entity framework 5 如何在实体框架中将多个实体合二为一(将复杂实体映射为单表) - How to combine several entities into one in entity framework (map complex entity into single table) 如何使用AutoMapper更新具有嵌套实体的实体,并使用实体框架保存更新的实体? - How do I update an entity with nested entities with AutoMapper and save the updated Entity with Entity Framework? 插入/更新多个到多个实体框架。我该怎么做? - Insert/Update Many to Many Entity Framework . How do I do it? 如何清除实体框架中的跟踪实体 - How do I clear tracked entities in entity framework 如何序列化实体框架实体(EF 5.0)? - How do I serialize Entity Framework entities (EF 5.0)? 如何在 Entity Framework LINQ To Entities 中进行联合? - How can I do a Union all in Entity Framework LINQ To Entities?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM