数据模型和类库 - 如何将虚拟属性添加到其他类库中的对象?

时间:2013-02-28 08:06:06

标签: c# entity-framework shared-libraries

我有两个用于数据模型和数据库上下文的库。

  1. 基础与对象

    public class Person
    {
        [Key]
        public int ID { get; set; }
        public string Name { get; set; }
        public string SName { get; set; }
        public bool IsSystemUser { get; set; }            
    }
    
  2. 扩展

    public class Vehicle
    {
      [Key]
      public int Id { get; set; }
      public string Name { get; set; }
      public string Plate { get; set; }    
      public virtual ICollection<Person> Users { get; set; }
    }
    
  3. 如何添加公共虚拟ICollection Vehicles {get;组;在第一类库中对象。 EF正在生成数据库。

2 个答案:

答案 0 :(得分:0)

使用扩展方法,您可以向类添加方法:

http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx

答案 1 :(得分:0)

  

在第二个库中,我想扩展第一个库中定义的Person,因此它可以与第二个库中的对象有很多关系。

您可以扩展基础库的Person类:

using BasePerson = BaseLibrary.Person;

public class Person : BasePerson
{
    public virtual ICollection Vehicles { get; set; }
}

这只有在你扩展DbContext时才有效:

using BaseContext = BaseLibrary.MyContext;

public class MyExtendedContext : BaseContext
{
    public new DbSet<Person> Persons { get; set; }
}

现在,当您使用MyExtendedContext时,您将能够访问Vehicles-collection。