johnny 5
johnny 5

Reputation: 21013

Map Properties Of a class to an interface

I'm just wondering if there is a way to Map Properties from a class to an interface with out changing their names.

Say you imported some entities from a Database

public partial class Post
{
    public int PostId {get; set;}
}

public partial  class Book
{
    public int BookId {get; set;}
}

and an interface:

public interface IHasID
{
   int Id {get; set;}
}

is there a way to inherit from this interface and just map the Properties using attributes like:

public partial class Post : IHasID
{
    [MetadataTypeAttribute(typeof(IHasID.Id))]
    public int PostId;
}   

I just want a simple way to do this without wrapping all of the code or changing the database. Is there a way to wrap the parital class to point its property as an interface property?

Upvotes: 3

Views: 1461

Answers (3)

Gert Arnold
Gert Arnold

Reputation: 109245

Use explicit implementation:

public partial class Post : IHasID
{
    public int PostId;

    int IHasID.Id
    {
        get => PostId;
        set => PostId = value;
    }
}

Usage example:

var ids = posts.Cast<IHasID>().Select(p => p.Id);

in which posts is an IEnumerable of Post instances.

The VB.Net syntax in this answer is definitely more elegant, but in VB you also have to cast to IHasID in order to use the Id property.

Upvotes: 2

rory.ap
rory.ap

Reputation: 35318

I'm not sure if it's worth pointing out just for the sake of knowledge that, if it were vb.net, you could do it just like this:

Partial Public Class Post
    Implements IHasID

    Public Property PostId As Integer Implements IHasID.Id
End Class

Upvotes: 2

Mike Eason
Mike Eason

Reputation: 9723

You could create an ID property which gets and sets your object's appropriate ID, like this:

public partial class Post : IHasID
{
    [NotMapped]
    public int Id 
    {
        get { return PostId; }
        set { PostId = value; }
    }

    public int PostId { get; set; }

    ...

You would of course do the same thing for Book.

Upvotes: 2

Related Questions