简体   繁体   中英

Complex relationship mappings in entity framework

I am building a reservation system. I have users in roles('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.

I have seen code like this at 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. 在此处输入图片说明

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. 2. If I am trying to delete a user of role client who have reservation in database I get following error.

The DELETE statement conflicted with the REFERENCE constraint "Reservation_Client". The conflict occurred in database "CRSDB", table "dbo.Reservations", column 'ClientId'. The statement has been terminated.

I checked the realtions in ERD and edmx model their is no cascade delete applied to them. 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.

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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