实体框架 - 处理相同对象的通用方法

时间:2016-03-09 11:24:42

标签: c# entity-framework oop

我有几个相同的对象组,每个对象组都包含映射到主表和耦合链接表的实体,例如

//group1
class OrderNote
{
    public int OrderNoteId {get; set;}
    public virtual ICollecton<OrderNoteTag> OrderNoteTags {get; set;}
}
class OrderNoteTag
{
    public int OrderNoteId {get; set;}
    public int TagId {get; set;}
}
//////
//group 2
class ClientNote
{
    public int ClientNoteId {get; set;}
    public virtual ICollecton<ClientNoteTag> ClientNoteTags {get; set;}
}
class ClientNoteTag
{
    public int ClientNoteId {get; set;}
    public int TagId {get; set;}
}
/////

现在,我需要一个允许我通过相同例程处理主对象的方法,因此我不必多次复制相同的代码。我的想法是为注释和标签设置一些基类,具体类型将从它们继承,并且该方法将接受注释的基类型。但我无法弄清楚如何声明和继承导航属性,因此它们映射到具体的标签类型,但可以作为基本类型处理。

这应该是这样的:

public class TagBase
{
    public int NoteId {get; set;}
    public int TagId {get; set;}
} 

public class NoteBase
{
    public int NoteId {get; set;}
    public virtual ICollecton<TagBase> NoteTags {get; set;}
}

//then we inherit
public class OrderNoteTag : TagBase {}

public class OrderNote : NoteBase
{
    //Here we should pass the concrete type OrderNoteTag to NoteTags collection somehow
}

// Then we have method, where we should be able to pass OrderNote or ClientNote
public void ProcessNote(NoteBase note)
{
    foreach(var tag in note.NoteTags){...blah-blah-blah...}
}

提前致谢。

1 个答案:

答案 0 :(得分:1)

考虑这种方法,它基于接口。现在您可以使用INote<INoteTag>类型代替NoteBase,查看我的答案的结尾,但是NoteTags循环内的foreach属性应该使用NoteTagsCustom()方法,我希望对你不重要。

<强>模型:

public interface INote<out T> where T : INoteTag
{
    int NoteId { get; set; }        
    IEnumerable<T> NoteTagsCustom();
}

public interface INoteTag
{
    int NoteTagId { get; set; }
    int TagId { get; set; }
}

public class OrderNote : INote<OrderNoteTag>
{
    [Key]
    public int NoteId { get; set; }
    public virtual ICollection<OrderNoteTag> NoteTags { get; set; }

    public IEnumerable<OrderNoteTag> NoteTagsCustom()
    {
        return NoteTags;
    }
}
public class OrderNoteTag : INoteTag
{
    [Key]
    public int NoteTagId { get; set; }
    [ForeignKey("OrderNote")]
    public int TagId { get; set; }
    public virtual OrderNote OrderNote { get; set; }
}

public class ClientNote : INote<ClientNoteTag>
{
    [Key]
    public int NoteId { get; set; }
    public virtual ICollection<ClientNoteTag> NoteTags { get; set; }

    public IEnumerable<ClientNoteTag> NoteTagsCustom()
    {
        return NoteTags;
    }
}
public class ClientNoteTag : INoteTag
{
    [Key]
    public int NoteTagId { get; set; }
    [ForeignKey("ClientNote")]
    public int TagId { get; set; }
    public virtual ClientNote ClientNote { get; set; }
}

<强>实现:

//important: INote<INoteTag> instead of NoteBase!
public void ProcessNote(INote<INoteTag> note)
{
    //important: NoteTagsCustom() instead of NoteTags!
    foreach(var tag in note.NoteTagsCustom()){...blah-blah-blah...}
}