实体框架DbEntityValidationException-找不到实体

时间:2016-01-23 15:11:48

标签: c# asp.net-mvc entity-framework

我想将数据从我的注册表格发布到我的数据库。首先我有一个非常常见的错误"实体类型 [Required] [Display(Name = "Name")] public string Name { get; set; } [Required] [Display(Name = "Surname")] public string Surname { get; set; } [Required] [Display(Name = "Email")] public string Email { get; set; } [Required] [DataType (DataType.Password)] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [Display(Name = "Password")] public string password { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "Confirm Password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } [Required] [Display(Name = "Address")] public string address { get; set; } [Required] [Display(Name = "PostVode")] [DataType(DataType.PostalCode)] public string postcode { get; set; } [Required] [Display(Name = "Phone Number")] public string number { get; set; } 不是当前上下文模型的一部分" 。我解决了,然后出现了另一个错误。所以现在出现的错误出现在SaveChanges部分,它是"无法找到实体密码"。我该如何解决这个问题?

以下是我的上下文的代码。

public sealed partial class MainPage : Page {
  private AudioGraph graph = null;
  private AudioDeviceInputNode deviceInputNode = null;

  public MainPage() {
    this.InitializeComponent();
  }

  private async Task CreateAudioGraph() {

    // Create an AudioGraph with default settings
    AudioGraphSettings settings = new AudioGraphSettings(AudioRenderCategory.Media);

    CreateAudioGraphResult result = await AudioGraph.CreateAsync(settings);

    if (result.Status != AudioGraphCreationStatus.Success) {
      // Cannot create graph
      await new ContentDialog() {
        Title = "Error",
        Content = String.Format("AudioGraph Creation Error because {0}", result.Status.ToString())
      }.ShowAsync();
      return;
    }

    graph = result.Graph;

    // Create a device input node
    CreateAudioDeviceInputNodeResult inputDeviceNodeResult = await graph.CreateDeviceInputNodeAsync(Windows.Media.Capture.MediaCategory.Other);

    if (inputDeviceNodeResult.Status != AudioDeviceNodeCreationStatus.Success) {
      // Cannot create device input node
      await new ContentDialog() {
        Title = "Error",
        Content = String.Format("DeviceInputNode Creation Error because {0}", inputDeviceNodeResult.Status.ToString()),
        PrimaryButtonText = "OK",
        IsSecondaryButtonEnabled = false
      }.ShowAsync();
      return;
    }
    deviceInputNode = inputDeviceNodeResult.DeviceInputNode;
  }

  private async void button_Click(object sender, RoutedEventArgs e) {
    await CreateAudioGraph();
  }
}

以下是我的控制器的代码

A problem occurred configuring root project 'moduleUpdater'.
Could not resolve all dependencies for configuration ':classpath'.

Could not find org.example.plugin:MyJavaPlugin:1.0-SNAPSHOT.

Searched in the following locations:
         .../moduleUpdater/repo/org/example/plugin/MyJavaPlugin/1.0-SNAPSHOT/maven-metadata.xml
         .../moduleUpdater/repo/org/example/plugin/MyJavaPlugin/1.0-SNAPSHOT/MyJavaPlugin-1.0-SNAPSHOT.pom
        .../moduleUpdater/repo/org/example/plugin/MyJavaPlugin/1.0-SNAPSHOT/MyJavaPlugin-1.0-SNAPSHOT.jar

Required by:           
         :moduleUpdater:unspecified

和模型 `

FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring root project 'user'.
> Could not resolve all dependencies for configuration ':classpath'.
   > Could not find com.code4reference:code4ReferencePlugin:1.1-SNAPSHOT.
     Searched in the following locations:
         .../Code4Reference-master/GradleExample/custom-plugin-1/repo/com/code4reference/code4ReferencePlugin/1.1-SNAPSHOT/maven-metadata.xml
         .../Code4Reference-master/GradleExample/custom-plugin-1/repo/com/code4reference/code4ReferencePlugin/1.1-SNAPSHOT/code4ReferencePlugin-1.1-20120816.164441-5.pom
         .../Code4Reference-master/GradleExample/custom-plugin-1/repo/com/code4reference/code4ReferencePlugin/1.1-SNAPSHOT/code4ReferencePlugin-1.1-20120816.164441-5.jar
     Required by:
         :user:unspecified

1 个答案:

答案 0 :(得分:0)

您需要确保User是DbContext的一部分。这就是我设置的方式:

public partial class MyDbEntities : DbContext
{
    public MyDbEntities()
        : base("name=MyDbEntities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Add the mapping class in here, instead of the setup
        modelBuilder.Configurations.Add(new UserMap());
    }

    public override int SaveChanges()
    {
        try
        {
            return base.SaveChanges();
        }
        catch (DbEntityValidationException ex)
        {
            string errorMessages = string.Join("; ", ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage));
            throw new DbEntityValidationException(errorMessages);
        }
    }

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

用户映射类,请注意它继承自EntityTypeConfiguration<User>,我认为这是你缺少的一点:

public class UserMap : EntityTypeConfiguration<User>
{
    public UserMap()
    {
        // Your original setup goes here
        this.ToTable("Users");
        this.Property(u => u.Name).IsRequired().HasMaxLength(256);
        this.Property(u => u.Surname).IsRequired().HasMaxLength(256);
        this.Property(u => u.Email).IsRequired().HasMaxLength(200);
        this.Property(u => u.password).IsRequired().HasMaxLength(100);
        this.Property(u => u.address).IsRequired();
        this.Property(u => u.postcode).IsRequired();
        this.Property(u => u.number).IsRequired();
    }
}

要么就是这样,要么就是你错过了。我的DbContext有一个静态构造函数来设置数据库初始化程序,如果你的已经没有,请尝试添加它:

static MyDbEntities()
{
    Database.SetInitializer<MyDbEntities>(null);
}