【问题标题】:Extend Entity framework 5 entity using partial class and map it to existing other entities使用部分类扩展 Entity framework 5 实体并将其映射到现有的其他实体
【发布时间】:2014-08-23 08:09:47
【问题描述】:

我还没有看到有人提出过这样的问题。因此,我为 EF fluent api 开发人员和 nopcommerce 插件开发人员创建了一个。

这是我想要做的:

我有一个产品实体,EF 可以使用它来生成数据库。我想在不修改原始类的情况下扩展产品实体。所以,我一直在尝试使用部分类。代码如下:

namespace Nop.Core.Domain.Catalog
{
    /// <summary>
    /// Represents a product
    /// </summary>
    public partial class Product : BaseEntity, ILocalizedEntity, ISlugSupported, IAclSupported, IStoreMappingSupported
    {
        //some fields here.
        public int ProductTypeId { get; set; }
        //.....
    }
}

现在当我像这样扩展类时:

namespace Nop.Core.Domain.Catalog
{
    public partial class Product : BaseEntity
    {
        public int RestaurantId { get; set; }

        public virtual Restaurant BelongRestaurant { get; set; } 
     }
}

它会抛出一个错误。

类型“Nop.Core.Domain.Catalog.Product”和类型 'Nop.Core.Domain.Catalog.Product' 都具有相同的简单名称 'Product' 等不能用于同一型号。一个中的所有类型 给定模型必须具有唯一的简单名称。使用“NotMappedAttribute”或 在 Code First fluent API 中调用 Ignore 以显式排除 来自模型的属性或类型。

这是我的映射文件的样子:

namespace Nop.Plugin.Misc.Plugin
{
    public partial class ProductMap : EntityTypeConfiguration<Nop.Core.Domain.Catalog.Product>
    {
        public ProductMap()
        {
            //Table
            this.ToTable(Settings.DATABASE_TABLE_NAME);

            //Primary Key
            this.HasKey(t => t.Id);

            //Property
            this.Property(t => t.Id)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            this.HasRequired(p => p.BelongRestaurant)
                .WithMany(r => r.Menu)
                .HasForeignKey(p => p.RestaurantId)
                .WillCascadeOnDelete(false);
        }
    }
}

有人可以帮忙吗?

【问题讨论】:

  • 它们都有相同的命名空间?
  • 我假设两个部分都在同一个程序集中?
  • @YuliamChandra 是的,它们在同一个命名空间中。
  • @GertArnold 不,他们在不同的项目中,有没有其他方法可以做到这一点?

标签: c# entity-framework ef-fluent-api


【解决方案1】:

partial class 只是一种语法糖,它允许您为一个类拥有多个文件。也就是说,您可以在同一个项目中创建尽可能多的部分类。

但是当你在另一个项目中使用一个类时,即使它是一个partial class,你也不能用partial class创建另一个文件来扩展它的功能。

阅读更多关于Partial Classes and Methods (C# Programming Guide)的信息。

【讨论】:

  • 非常感谢,所以,这是因为它们不在同一个程序集中,有没有其他方法可以解决它?
  • 您可以使用反射将代码注入到另一个项目的类中,但这有点太极端了。
  • Ekk,我喜欢你的回答清楚地说明为什么原始问题无法通过部分课程解决,但你对如何做玉轩想要的事情有任何想法,即添加东西到来自另一个程序集的实体?还是创建可扩展的实体?
猜你喜欢
  • 2013-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-13
  • 1970-01-01
  • 1970-01-01
  • 2015-10-03
  • 2016-08-05
相关资源
最近更新 更多