简体   繁体   English

管理实体框架中的复杂类型?

[英]Manage Complex types in Entity Framework?

I have the following entity models. 我有以下实体模型。 When I try to save a new User object that contains a new Account, it throws a DBUpdateException: An error occurred while saving entities that do not expose foreign key properties for their relationships. 当我尝试保存包含新帐户的新User对象时,它会抛出DBUpdateException:保存不公开其关系的外键属性的实体时发生错误。

Is it possible to provide mapping for the two objects without adding foreign keys to my model. 是否可以为两个对象提供映射,而无需向模型添加外键。 I hate the idea of having foreign keys in my models. 我讨厌在我的模型中使用外键的想法。 If there is no other solution, how would i resolve this issue using foreign keys? 如果没有其他解决方案,我将如何使用外键解决此问题?

public class User
{
   public virtual int Id { get; set; }
   public virtual Account Account { get; set; }
}

public class Account
{
   public virtual int Id { get; set; }
}

Are either of these classes really "complex types" or are they both entities with their own corresponding table? 这些类中的任何一个真的是“复杂类型”还是它们都是具有自己相应表的实体?

If they're entities, you can indeed configure EF to not require foreign key properties in the classes themselves. 如果它们是实体,您确实可以将EF配置为不需要类本身中的外键属性。 In your DbContext class, override OnModelCreating and add some configuration code like this: 在DbContext类中,重写OnModelCreating并添加一些配置代码,如下所示:

modelBuilder.Entity<User>().HasRequired(u => u.Account).WithRequiredPrincipal();

If I've gotten that right, that will configure a "required:required" relationship between User and Account without needing any foreign key properties on either class. 如果我已经做到了这一点,那将在用户和帐户之间配置“required:required”关系,而不需要任何类的任何外键属性。

您必须从类Account删除属性Id ,否则实体框架会将类Account视为实体而不是复杂类型。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM