c# - 使用值注入(inject)器映射不同的属性值

标签 c# sql-server-2008 entity-framework inheritance valueinjecter

我有一个从基类派生的表。因此,派生表将具有与基表相同的 id。 喜欢

public class Animal
{
public int AnimalId{get; set;}
public string Name{get;set;}
}

public class Man:Animal
{
//Primary key as well as foreign key will be AnimalId. 
public string Communicate{get;set;}
}

现在,虽然我可以使用 ManId 作为数据库中的主键,并使用 Fluent api 让类知道 ManId 是基类 AnimalId,但我无法在我的 poco 类和编程中直接使用 ManId。

因此,我使用了 viewmodel,给出了属性名称 ManId 以在我的类和 View 中使用。我正在使用 ValueInjector 在模型和 View 模型之间进行映射。

我整个早上都陷入并寻求解决方案的问题是: valueinjector 无法将 AnimalId 注入(inject) ManId,因为名称不同。

我发现解决方案可能是..使用约定注入(inject)来覆盖默认值,但我无法正确实现它。

public class PropertyMismatch:ConventionInjection
{
    protected override bool Match(ConventionInfo c)
    {
        return ((c.TargetProp.Name == "ManId" && c.SourceProp.Name == "AnimalId") ||
            (c.SourceProp.Name==c.TargetProp.Name &&                            c.SourceProp.Value==c.TargetProp.Value));

    }


}

如果有人知道解决方案,对我应该有很大帮助。非常感谢所有观众和求解者。

最佳答案

试试这个:

class Program
{
    static void Main( string[] args )
    {
        Animal animal = new Animal() { AnimalId = 1, Name = "Man1" };
        Man man = new Man();
        man.InjectFrom<Animal>( animal );
    }
}

public class Animal:ConventionInjection
{
    public int AnimalId { get; set; }
    public string Name { get; set; }

    protected override bool Match( ConventionInfo c )
    {
        return ((c.SourceProp.Name == "AnimalId") && (c.TargetProp.Name == "ManId"));
    }
}

public class Man : Animal
{

    public int ManId { get; set; } 
    public string Communicate { get; set; }
}

关于c# - 使用值注入(inject)器映射不同的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20461396/

相关文章:

c# - CPU、内存使用、线程池使用 - ASP NET core 身份未确认的邮件用户删除处理 - 在应用程序中还是单独的应用程序?

c# - SQL Server 2008 回归时间的 DATE 数据类型!

c# - 按行和列名称从 DataTable 中获取值

c# - 如何使用单独的逗号 (,) 绑定(bind)下拉列表中的两列值

c# - 加入并包含在 Entity Framework 中

c# - 无法使用 Nullable DbGeography

c# - VS2010/C# 中的全局 "using"指令?

c# - 多次异步请求相同的 Web 服务

c# - 列出线程安全?

sql-server-2008 - 数据库邮件的脚本设置