简体   繁体   English

实体框架中的复杂关系映射

[英]Complex relationship mappings in entity framework

I am building a reservation system. 我正在建立一个预订系统。 I have users in roles('admin', 'client', 'employee', 'student'). 我有角色(“ admin”,“ client”,“ employee”,“ student”)的用户。

Each reservation must be associated with a user of role client, it might be assigned to user of role employee and might also be assigned to user of role student. 每个保留必须与角色客户的用户相关联,它可能被分配给角色员工的用户,也可能被分配给角色学生的用户。

So in my reservation class I have properties of type User and I have marked them with [ForeignKey("AnytypeId")] attribute to hint EF for relations. 因此,在预订类中,我具有用户类型的属性,并用[ForeignKey(“ AnytypeId”)]属性标记了它们,以提示EF关系。

I have seen code like this at http://blog.stevensanderson.com/2011/01/28/mvcscaffolding-one-to-many-relationships/ 我在http://blog.stevensanderson.com/2011/01/28/mvcscaffolding-one-to-many-relationships/上看到了这样的代码

public class Reservation
{

    public int ReservationID
    {
        get;
        set;
    }

    [Required(ErrorMessage="Please provide a valid date")]
    public DateTime ReservationDate
    {
        get;
        set;
    }
    public DateTime ReservationEnd { get; set; }
    public DateTime EntryDate
    {
        get;
        set;
    }
    public DateTime UpdatedOn
    {
        get;
        set;
    }
    public decimal Ammount
    {
        get;
        set;
    }

    public decimal? Discount { get; set; }

    [DataType(DataType.MultilineText)]
    public string ServiceDetails { get; set; }

    [DataType(DataType.MultilineText)]        
    public string Remarks { get; set; }

    public string VoucherNumber { get; set; }

    public int ServiceID
    {
        get;
        set;
    }
    public Service Service
    {
        get;
        set;
    }

    public string EmployeeId { get; set; }
    [ForeignKey("EmployeeId")]
    public User Employee { get; set; }


    public string ClientId { get; set; }
    [ForeignKey("ClientId")]
    public User Client { get; set; }


    public string StudentId { get; set; }
    [ForeignKey("StudentId")]
    public User Student { get; set; }

}
public class User
{

    //[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    //public Guid UserId { get; set; }

    [Key]
    [Required(ErrorMessage = "User Name is required")]
    [Display(Name = "User Name")]
    [MaxLength(100)]        
    public string UserName { get; set; }

    [Required]
    [MaxLength(64)]
    public byte[] PasswordHash { get; set; }

    [Required]
    [MaxLength(128)]
    public byte[] PasswordSalt { get; set; }

    [Required(ErrorMessage = "Email is required")]
    [DataType(DataType.EmailAddress)]
    [MaxLength(200)]
    public string Email { get; set; }

    [MaxLength(200)]
    public string Comment { get; set; }

    [Display(Name = "Approved?")]
    public bool IsApproved { get; set; }

    [Display(Name = "Crate Date")]
    public DateTime DateCreated { get; set; }

    [Display(Name = "Last Login Date")]
    public DateTime? DateLastLogin { get; set; }

    [Display(Name = "Last Activity Date")]
    public DateTime? DateLastActivity { get; set; }

    [Display(Name = "Last Password Change Date")]
    public DateTime DateLastPasswordChange { get; set; }

    public string address { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string Phone { get; set; }

    public bool? IsActive { get; set; }

    public int? ClientTypeID { get; set; }
    public virtual ClientType ClientType { get; set; }

    public virtual ICollection<Role> Roles { get; set; }

    public DateTime? PackageValidity { get; set; }


    public virtual ICollection<Reservation> Reservations { get; set; }


}

public class UserMap : EntityTypeConfiguration<User>
{
    public UserMap()
    {
        this.HasMany(u => u.Roles)
         .WithMany(r => r.Users)
         .Map(m =>
         {
             m.ToTable("RoleMemberships");
             m.MapLeftKey("Username");
             m.MapRightKey("RoleName");
         });
    }
}

Now as I run my mvc3 EF code first app database created for me on the fly with following ERD and edmx model. 现在,当我运行我的mvc3 EF代码时,首先使用以下ERD和edmx模型为我动态创建了应用数据库。 在此处输入图片说明

Now few problems that I am having: 1. When I am listing all the users of role clients their reservation property is showing always 0 even if their are reservations available in database. 现在我遇到的几个问题是:1.当我列出角色客户端的所有用户时,即使他们是数据库中可用的保留,他们的保留属性也始终显示为0。 2. If I am trying to delete a user of role client who have reservation in database I get following error. 2.如果我尝试删除在数据库中有保留的角色客户端用户,则会出现以下错误。

The DELETE statement conflicted with the REFERENCE constraint "Reservation_Client". DELETE语句与REFERENCE约束“ Reservation_Client”冲突。 The conflict occurred in database "CRSDB", table "dbo.Reservations", column 'ClientId'. 在数据库“ CRSDB”的表“ dbo.Reservations”的“ ClientId”列中发生了冲突。 The statement has been terminated. 该语句已终止。

I checked the realtions in ERD and edmx model their is no cascade delete applied to them. 我检查了ERD和edmx模型中的区域,是否没有应用级联删除。 How can I instruct EF to delete all the reservations when deleting user of role client but not for users of role employee or student. 在删除角色客户的用户但不删除角色员工或学生的用户时,如何指示EF删除所有保留。

This code does the trick 这段代码可以解决问题

public class Reservation
{

    public int ReservationID
    {
        get;
        set;
    }

    [Required(ErrorMessage="Please provide a valid date")]
    public DateTime ReservationDate
    {
        get;
        set;
    }
    public DateTime ReservationEnd { get; set; }
    public DateTime EntryDate
    {
        get;
        set;
    }
    public DateTime UpdatedOn
    {
        get;
        set;
    }
    public decimal Ammount
    {
        get;
        set;
    }

    public decimal? Discount { get; set; }

    [DataType(DataType.MultilineText)]
    public string ServiceDetails { get; set; }

    [DataType(DataType.MultilineText)]        
    public string Remarks { get; set; }

    public String  PaymentMethod { get; set; }
    public string VoucherNumber { get; set; }

    public int ServiceID
    {
        get;
        set;
    }
    public virtual Service Service
    {
        get;
        set;
    }


    public string EmployeeID { get; set; }
    [ForeignKey("EmployeeID")]
    public virtual User Employee { get; set; }


    public string ClientID { get; set; }
    [ForeignKey("ClientID")]
    public virtual User Client { get; set; }


    public string StudentID { get; set; }
    [ForeignKey("StudentID")]
    public virtual User Student { get; set; }


}

public class ReservationMap : EntityTypeConfiguration<Reservation>
{
    public ReservationMap()
    {
        this.HasOptional(r => r.Client).WithMany().WillCascadeOnDelete(true);
        this.HasOptional(r => r.Employee).WithMany().WillCascadeOnDelete(false);
        this.HasOptional(r=>r.Student).WithMany().WillCascadeOnDelete(false);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM