我可以在NHibernate中使用接口作为DTO吗?

时间:2013-11-22 21:03:35

标签: c# nhibernate dto modularity

我通过查询减少了通过线路传输的字节数,并且正在编写...我意识到我应该能够将接口传递给QueryOver对象并获取该接口属性的指定列。

是否可以将接口传递给QueryOver对象的select或类似命令?它只会返回“映射”到接口的列吗?

示例:

Repository
    .QueryOver<MyTable>()
    .Select(table => table as IJustWantTheseColumnsInterface)
    .Execute(Parameters);
//or

Repository
    .QueryOver<MyTable>()
    .Select<IJustWantTheseColumnsInterface>()
    .Execute(Parameters);

//...

public class Table : IJustWantTheseColumnsInterface
{
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }
    public Phone Phone { get; set; }
    public DateTime BirthDate { get; set; }
    public Occupation Occupation { get; set; }
    public Employer Employer { get; set; }
    //etc...
}

public interface IJustWantTheseColumnsInterface
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Phone Phone { get; set; }
}

1 个答案:

答案 0 :(得分:0)

为什么不能只创建一个只映射到那些列的第二个实现?

public class Table : IJustWantTheseColumnsInterface
{
    public virtual int Id { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string MiddleName { get; set; }
    public virtual string LastName { get; set; }
    public virtual Address Address { get; set; }
    public virtual Phone Phone { get; set; }
    public virtual DateTime BirthDate { get; set; }
    public virtual Occupation Occupation { get; set; }
    public virtual Employer Employer { get; set; }
}

public class SameTable : IJustWantTheseColumnsInterface
{
    public virtual int Id { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual Phone Phone { get; set; }
}

public interface IJustWantTheseColumnsInterface
{
    int Id { get; set; }
    string FirstName { get; set; }
    string LastName { get; set; }
    Phone Phone { get; set; }
}

public class SameTableMap : ClassMap<SameTable>
{
    public SameTableMap()
    {
        Table("Table");
        Id(x => x.Id, "ID");

        Map(x => x.FirstName, "FIRST_NAME");
        Map(x => x.LastName, "LAST_NAME");

        Reference(x => x.Phone, "PHONE_ID");
    }
}

您也可以使用Interface作为Class for Class。

同样,如果Phone类属于Table类中的接口IPhone类型。您可以指定要返回的实现。

public interface IJustWantTheseColumnsInterface
{
    ...
    IPhone Phone { get; set; }
    ...
}

public class SameTableMap : ClassMap<SameTable>
{
    public SameTableMap()
    {
        ...
        Reference(x => x.Phone, "PHONE_ID").Class(typeof(Phone));
        ...
    }
}

现在,如果你想获得你的部分实体

IJustWantTheseColumnsInterface someVariable = session.Get<SameTable>();