2011-12-24 77 views
1

有人可能會提出一個C#限制的解決方法嗎?我需要兩種不同的類型來源於相同的基類型。在我的例子中,員工和用戶是人。員工也可以是用戶(反之亦然)。看起來這是C#中不支持的多重繼承。我已閱讀http://www.codeproject.com/KB/architecture/smip.aspx,這似乎不符合我的方案。實體框架4.1,每種類型的表繼承

public abstract class Person 
    { 

    public int ID { get; set; } 

    public string Name { get; set; } 

    public string Email { get; set; } 
    } 

    public class Employee : Person 
    { 

    public string Number { get; set; } 

    public System.DateTime HireDate { get; set; } 
    } 

    public class User : Person 
    { 

    public string Password { get; set; } 

    public bool Active { get; set; } 
    } 

    public class CfTestContext : DbContext 
    { 

    public DbSet<Employee> Employees { get; set; } 

    public DbSet<User> Users { get; set; } 

    public DbSet<Person> People { get; set; } 


    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 

     modelBuilder.Conventions.Remove<IncludeMetadataConvention>(); 

     modelBuilder.Entity<Person>().ToTable("People"); 

     modelBuilder.Entity<Employee>().ToTable("Employees"); 

     modelBuilder.Entity<User>().ToTable("Users"); 
    } 
    } 

    public class CreateCfTestDatabase : DropCreateDatabaseAlways<CfTestContext> 
    { 

    protected override void Seed(CfTestContext context) 
    { 

     // Abraham Lincoln hired as an Employee on February 12th. 

     // Abraham doesn't need access as a User because he doesn't use the Purchasing application. 

     context.Employees.Add(new Employee { Name = "Abraham Lincoln", Email = "[email protected]", Number = "107124", HireDate = System.DateTime.Parse("2/12/2000") }); 

     // George Washington added as a User on July 4th. 

     // George is a consultant, so he will never become an Employee. 

     context.Users.Add(new User { Name = "George Washington", Email = "[email protected]", Password = "xT76#a2", Active = true }); 

     context.SaveChanges(); 

     // Make Abraham Lincoln a User on September 29th. 

     // Abraham received training and now needs to use the Purchasing application 

     Employee employee = context.Employees.Where(t => t.Name == "Abraham Lincoln").FirstOrDefault(); 

     context.Users.Add(new User { Password = "C1x$av38", Active = true, ID = employee.ID }); // this does not produce the desired results. 

     context.SaveChanges(); 

     base.Seed(context); 
    } 
    } 

回答

1

你是對的,不可能在C#中創建多個繼承對象。但是你可以通過在你的模型中創建一個ComplexType來解決這個問題(例如Login)並添加Password和Active屬性,將Login屬性添加到person對象中。然後,您可以通過檢查Person對象上的Login.Active來檢查用戶是否具有活動的登錄信息。

+0

謝謝Espen及時給您答覆。 – tebo