Entity Framework添加导航属性运行时提示生成Model失败解决方法



项目使用Entity Framework Power Tools Beta 2生成Models,后来在Pet.PersonId和Petson.Id间添加了主外键, 因为有手工修改过Models,不能用工具重新生成,只能手工添加导航属性相关代码:

Person.cs:
using System;
using System.Collections.Generic;

namespace ConsoleApplication1.Models
{
    public class Person
    {
        public Person()
        {
            this.Pets = new List<Pet>();
        }

        public int Id { get; set; }
        public string Name { get; set; }

        public virtual ICollection<Pet> Pets { get; set; }
    }
}

Pet.cs:
using System;
using System.Collections.Generic;

namespace ConsoleApplication1.Models
{
    public class Pet
    {
        public int Id { get; set; }
        public int PersonId { get; set; }
        public string Name { get; set; }

        public virtual Person Person { get; set; }
    }
}

PetMap.cs:
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.ModelConfiguration;

namespace ConsoleApplication1.Models.Mapping
{
    public class PetMap : EntityTypeConfiguration<Pet>
    {
        public PetMap()
        {
            // Primary Key
            this.HasKey(t => t.Id);

            // Properties
            this.Property(t => t.Name)
                .HasMaxLength(50);

            // Table & Column Mappings
            this.ToTable("Pet");
            this.Property(t => t.Id).HasColumnName("Id");
            this.Property(t => t.PersonId).HasColumnName("PersonId");
            this.Property(t => t.Name).HasColumnName("Name");

            this.HasOptional(t => t.Person)
                .WithMany(t => t.Pets)
                .HasForeignKey(d => d.PersonId);

        }
    }
}

运行报错,提示:
引用内容 引用内容
One or more validation errors were detected during model generation:

System.Data.Edm.EdmAssociationType: : Multiplicity conflicts with the referential constraint in Role 'Pet_Person_Target' in relationship 'Pet_Person'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.

经多次测试比较,最终发现PetMap类需做如下修改:

this.HasRequired(t => t.Person)
    .WithMany(t => t.Pets)
    .HasForeignKey(d => d.PersonId);

HasOptional和HasRequired的区别:

引用内容 引用内容
HasOptional:Configures an optional relationship from this entity type. Instances of the entity type will be able to be saved to the database without this relationship being specified. The foreign key in the database will be nullable.
HasRequired:Configures a required relationship from this entity type. Instances of the entity type will not be able to be saved to the database unless this relationship is specified. The foreign key in the database will be non-nullable.

后记:最开始以为这个错误和表字段允许空有关,其实是没有关系的,它更多和Pet类PersonId属性的类型有关系,若PersonId类型为Nullable<int>,则不会有上述错误。

评论: 0 | 引用: 0 | 查看次数: 5583
发表评论
登录后再发表评论!