Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to generalize classes with the same structure but different property names?
    text
    copied!<p>The database I'm working with on a Windows Forms application has a lot of tables that consist of a primary key int identity field, a varchar description and a one-to-one relationship with another table where its id and description are used.</p> <p>One example of my C# POCOs mapped to the database using Entity Framework Code First is:</p> <pre><code>public class OtherClass { public int Id { get; set; } public string Description { get; set; } } public class Foo { public int Id { get; set; } public string Description { get; set; } public OtherClass OtherClassProperty { get; set; } } </code></pre> <p>Because those classes like "Foo" all share the same structure, I'm creating one basic form that should be able to work with all classes like this one.</p> <p>My problem is that all of those classes have different property names for its Id and Description (sometimes called Name, for example). Not to mention that the other class they reference is always different.</p> <p>My first thought was to create an interface requiring the implementation of properties with fixed names: Id, Description, KeyId, KeyDescription. Those properties would be implemented on each class but only pointing to the "real properties". Like this:</p> <pre><code>public class Foo : MyInterface { public int Id { get; set; } public string Description { get; set; } public OtherClass OtherClassProperty { get; set; } //Interface implementation public int CommonId { get { return this.Id; } set { this.Id = value; } } public int CommonDescription { get { return this.Description; } set { this.Description = value; } } public int CommonKeyId { get { return this.OtherClassProperty.Id; } set { this.OtherClassProperty.Id = value; } } public int CommonKeyDescription { get { return this.OtherClassProperty.Description; } set { this.OtherClassProperty.Description = value; } } } </code></pre> <p>I have the impression that there might be a better solution for this. I can also imagine implementing property attributes and using reflection to check at runtime and get the properties.</p> <p>Would anyone have a suggestion for this situation?</p> <p>Thanks in advance.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload