为实体框架 (4.2) 实体使用接口时出错 [英] error when using interfaces for Entity Framework (4.2) entities

查看:26
本文介绍了为实体框架 (4.2) 实体使用接口时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用最新版本的实体框架 (4.2) 并尝试为我的实体实现接口,但由于某种原因,它没有编译.它抛出错误Cannot convert expression type ICollection to return type ICollection".如果我不为实体使用接口,则不会出现此错误.

I am using the the latest version of Entity Framework (4.2) and trying to implement interfaces for my Entities and for some reason, it isn't compiling. it is throwing an error "Cannot convert expression type ICollection<IOrder> to return type ICollection<Order>". if I don't use interfaces for the entities, then I don't get this error.

我有一个单独的接口项目(用于存储库和服务等),我需要将这些方法中的 EF 实体作为参数传递,我不想传递其中的实际实体,因为这将需要接口项目依赖于 EF 实体.

I have a separate project for interfaces (for repositories and services etc) and I need to pass the EF entities in those methods as parameters and I don't want to pass the actual entities in them, because that will require the interface project to have a dependency on the EF entities.

我的目标与本文中提到的目标有些相似我可以从实体中抽象出实体框架吗?

my goal is somewhat similar to the one mentioned in this post Can I abstract Entity Framework away from my Entities?

这是示例.我只是在这里放了一个样本,我的实际实体不同,但问题是一样的.

here is the sample. I just put a sample here, my actual entities are different, but the problem is same.

public interface IOrder
{
    int OrderId { get; set; }
    int CustomerId { get; set; }
    ICustomer Customer { get; set; }
}

public class Order : IOrder
{
    public int OrderId { get; set; }
    public int CustomerId { get; set; }
    ICustomer Customer { get; set; }
}

public interface ICustomer
{
    int CustomerId { get; set; }
    ICollection<IOrder> Orders { get; set; }
}

public class Customer : ICustomer
{
    public int CustomerId { get; set; }
    ICollection<IOrder> Orders { get; set; }
}

public class OrderMap : EntityTypeConfiguration<Order>
{
    this.HasOptional(t => t.Customer)
    .WithMany(t => t.Orders) //error comes from this line
    .HasForeignKey(d => d.CustomerId);
}

推荐答案

实体框架无法使用接口.您的导航属性必须使用真实的实体类型(映射类).

Entity framework is not able to work with interfaces. Your navigation properties must use the real entity types (mapped classes).

这篇关于为实体框架 (4.2) 实体使用接口时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆