简体   繁体   中英

Use two model classes using same table in entity framework - mvc4

We are trying to use the the same table, tblLogin which has the below fields: UserName,UserType,UserEmail,Password.

I have two types of forms. One for Login where only 2 fields are required ie. userName and Password. Another form has all 4 fields for CRUD functionality.

I have created one model class with DataAnnotation - [Required] for 2 columns and have created another class with [Required] for all four columns as per need.

It gives me error:

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: The entity types 'AdminUser' and 'Login' cannot share table 'tblLogin' because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary 

Code is as below for 2 model classes:

Login.cs

[Table("tblLogin")]
public class Login
{
    [Key]
    public int adminId { get; set; }
    public string adminName { get; set; }
    [Required(ErrorMessage="Please provide your Email ID",AllowEmptyStrings=false)]
    [DataType(System.ComponentModel.DataAnnotations.DataType.EmailAddress)]
    public string adminEmail { get; set; }
    [Required(ErrorMessage="Please provide your password",AllowEmptyStrings=false)]
    [DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
    public string adminPassword { get; set; }
    public string adminType { get; set; }
}

AdminUser.cs

[Table("tblLogin")]
public class AdminUser
{
    [Key]
    public int adminId { get; set; }
    [Required]
    public string adminName { get; set; }
    [Required(ErrorMessage = "Please provide your Email ID", AllowEmptyStrings = false)]
    [DataType(System.ComponentModel.DataAnnotations.DataType.EmailAddress)]
    public string adminEmail { get; set; }
    [Required(ErrorMessage = "Please provide your password", AllowEmptyStrings = false)]
    [DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
    public string adminPassword { get; set; }
    [Required]
    public string adminType { get; set; }
}

I am new to mvc4.

WE did find the answer by using just one model class that is login.cs as it was and in our controller under the insert and edit function we wrote the below code and successfully achieved server side validation.

if (string.IsNullOrEmpty(u.adminName))
                ModelState.AddModelError("adminName", "Name field is Required");
if (string.IsNullOrEmpty(u.adminType))
                ModelState.AddModelError("adminType", "Please select the type of User");

Thanks for your suggestions

在例外情况下,附加信息说:实体类型'AdminUser'和'Login'无法共享表'tblLogin'对于每个数据库表,您只能创建一个类。

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