如何实现ForeignKey属性到接口

时间:2012-11-15 08:04:30

标签: entity-framework-4 attributes

ForeignKeyAttribute不能在Interface上工作吗?

public class Client: CompanyForeignKeyMapper
{
     public int Client;
}

public class CompanyForeignKeyMapper
{
     [ForeignKeyAttribute("Company")]
     int ClientId;
}

此代码工作正常。但是当我将类CompanyForeignKeyMapper更改为接口

public interface ICompanyForeignKeyMapper


public class Client: ICompanyForeingKeyMapper --> changed to interface

该属性似乎不起作用。

1 个答案:

答案 0 :(得分:0)

当您在第二个示例中声明Client类时,它不再继承自CompanyForeignKeyMapper类,因此它将没有ClientId字段。如果您希望它继承自CompanyForeignKeyMapper并且要实现ICompanyForeingKeyMapper接口,请将其声明为:

public class Client: CompanyForeignKeyMapper, ICompanyForeingKeyMapper

或者,您可以将ClientId定义为接口的字段,在这种情况下,Client类必须实现它并可以向其添加自己的ForeignKeyAttribute:

public interface ICompanyForeignKeyMapper
{
    int ClientId;
}


public class Client: ICompanyForeignKeyMapper
{
    [ForeignKeyAttribute("Company")]
    int ClientId;
}