brocrow
brocrow

Reputation: 65

c# MVC - inheritance and interfaces

I'm somewhat new to all this. So please bear with me.

I have a class called CrmObject which are inherited by a few other classes like Contact. Now I want to code an interface to use for all child-classes of CrmObject. I Need that for Unity.MVC repositories. Right now I have an interface for each child-class, but there should be a better way to do this and that's why I'm here. I would be glad for links and examples for this.

Pocos:

public class CrmObject
{
    [Key]
    [Column(Order = 0)]
    public int Id { get; set; }
    public bool IsProcessed { get; set; }
    public string Error { get; set; }
    public long PartnerOID { get; set; }
    public OrdnungsbegriffeTypeType OrdnungsbegriffTyp { get; set; }
    [Required]
    public string OrdnungsbegriffTypString { get; set; }
    public string OrdnungsbegriffWert { get; set; }
    public CrmJob Job { get; set; }
    [ForeignKey("Job")]
    [Column(Order = 1)]
    public int JobId { get; set; }
}

[Table("Contacts")]
    public class Contact: CrmObject
    {
        public DateTime KontaktAm { get; set; }
        public string ErstelltVon { get; set; }
        public DateTime ErstelltAm { get; set; }
        public string Vorlage { get; set; }
}

[Table("Tasks")]
    public class Task: CrmObject
    {
        public long AufgabeOID { get; set; }
        public string ExterneId { get; set; }
        public string Aufgabendefinitionsname { get; set; }
}

Interface:

public interface ICrmObjectRepository
{
    void Add(CrmObject o);
    void AddRange(IEnumerable<CrmObject> o);
    void Remove(int crmObjectId);
    IEnumerable<CrmObject> GetObjectsByJobId(int crmJobId);
    CrmObject FindById(int crmObjectId);
}

I'd for example like to not only use the CrmObject-type as parameter for the Add function, but all children of CrmObject, too.

Maybe I'm all wrong and the way I want to do this is stupid, impossible or both. I'd really love for people with more experience to give me hints on how to do this best. If there is any additional Information needed just ask for it.

Thanks in advance

Upvotes: 1

Views: 176

Answers (2)

blogprogramisty.net
blogprogramisty.net

Reputation: 1782

You may inherited interface like this:

public interface IChildCrmObject : ITask, IContact, ICrmObject
{
    ....
}

Upvotes: 0

Cleverguy25
Cleverguy25

Reputation: 503

Look into generics in c#. https://msdn.microsoft.com/en-us/library/512aeb7t.aspx

Basically your interface will look something like this:

public interface ICrmObjectRepository<T> where T: CrmObject   
{
    void Add(T o);
    void AddRange(IEnumerable<T> o);
    void Remove(int crmObjectId);
    IEnumerable<T> GetObjectsByJobId(int crmJobId);
    TFindById(int crmObjectId);
}

Notice the where T: CrmObject. This is a constraint.

https://msdn.microsoft.com/en-us/library/d5x73970.aspx

Upvotes: 1

Related Questions