【问题标题】:Interface as field in EntityFramework Core [duplicate]作为 EntityFramework Core 中的字段的接口 [重复]
【发布时间】:2021-01-20 14:05:40
【问题描述】:

有没有办法在 EF Core 中将接口用作类的字段(CodeFirst,最后一个版本到第 5.0 天)?

public class Order
{
   public int Id { get; set;}
   public IUser CreatedBy { get; set; }
}

【问题讨论】:

  • @RomanRyzhiy,谢谢。 EF Core 应该和 EF 一样吗?
  • 不适用于导航属性。通过值转换,您可以将接口属性添加到存储在数据库中的单个字段中的模型中。
  • Ivan StoevPalle Due 关闭作为重复的问题询问不同的框架?事件标签显示它,别介意第一句话说EF Core

标签: c# entity-framework .net-core entity-framework-core ef-core-5.0


【解决方案1】:

您可以使用 db 中不存在的导航属性接口。但是对于 Db 列,您需要具体的类。

在您的情况下,您有两种方法:

public class Order
{
[Key]
   public int Id { get; set;}
[ForeignKey]
   public int UserId CreatedBy { get; set; }
}

这样您就可以将 UserId 保存到 Db 并重复使用它。首选这种方式。

另一种方式:

public class Order
{
   [Key]
   public int Id { get; set;}
   [NotMapped]
   public IUser CreatedBy { get; set; }
}

但是只要内存中存在 Order 实例,这种方式 IUser 就可以使用。

【讨论】:

  • spasibo...无论如何,我认为这种情况没有完美的解决方案...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-27
  • 2021-08-02
  • 1970-01-01
  • 2021-10-16
  • 2022-01-27
  • 2012-10-05
相关资源
最近更新 更多