实体框架代码优先:使用注解设置一对一的外键关联 [英] Entity Framework Code First : Setting up One-To-One foreign key association using Annotations

查看:30
本文介绍了实体框架代码优先:使用注解设置一对一的外键关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用外键关联(一对一)关联以下两个实体.

I have following two Entities that I am trying to relate (one to one) using foreign key associations.

public class StandardRack {
    public int Id {get;set}
    public StandardRelay StandardRelay {get;set} 
}

public class StandardRelay {
    public int Id {get;set} 

    public int StandardRack_Id {get;set;}
    [Required][ForeignKey("StandardRack_Id")]
    public StandardRack StandardRack { get; set; }
}

这会引发 ModelValidationException.任何想法为什么不能配置这种看似简单的一对一双向关系.

This throws ModelValidationException. Any ideas why such a seemingly simple one-to-one bidirectional relationship cannot be configured.

这里是例外:

System.Data.Entity.ModelConfiguration.ModelValidationException 被捕获Message=在模型生成过程中检测到一个或多个验证错误:

System.Data.Entity.ModelConfiguration.ModelValidationException was caught Message=One or more validation errors were detected during model generation:

System.Data.Edm.EdmAssociationEnd:: 多重性在关系StandardRelay_StandardRack"中的角色StandardRelay_StandardRack_Source"中无效.由于 Dependent Role 属性不是关键属性,因此 Dependent Role 的重数上限必须为 * .

System.Data.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'StandardRelay_StandardRack_Source' in relationship 'StandardRelay_StandardRack'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be �*�.

源=实体框架堆栈跟踪:在 System.Data.Entity.ModelConfiguration.Edm.EdmModelExtensions.ValidateAndSerializeCsdl(EdmModel 模型,XmlWriter 编写器)在 System.Data.Entity.ModelConfiguration.Edm.EdmModelExtensions.ValidateCsdl(EdmModel 模型)在 System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)在 System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)在 System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)在 System.Data.Entity.Internal.RetryLazy2.GetValue(TInput input)在 System.Data.Entity.Internal.LazyInternalContext.InitializeContext()在 System.Data.Entity.Internal.InternalContext.Initialize()在 System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)在 System.Data.Entity.Internal.Linq.InternalSet1.Initialize()在 System.Data.Entity.Internal.Linq.InternalSet1.GetEnumerator()在 System.Data.Entity.Infrastructure.DbQuery1.System.Collections.Generic.IEnumerable.GetEnumerator()在 System.Collections.Generic.List1..ctor(IEnumerable1 collection)在 System.Linq.Enumerable.ToList[TSource](IEnumerable`1 源)在 TestApplication.MainWindow.Window_Loaded(Object sender, RoutedEventArgs e) 在 D:RailwayProjectsRelayAnalysisTestApplicationMainWindow.xaml.cs:line 33内部异常:

Source=EntityFramework StackTrace: at System.Data.Entity.ModelConfiguration.Edm.EdmModelExtensions.ValidateAndSerializeCsdl(EdmModel model, XmlWriter writer) at System.Data.Entity.ModelConfiguration.Edm.EdmModelExtensions.ValidateCsdl(EdmModel model) at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo) at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) at System.Data.Entity.Internal.RetryLazy2.GetValue(TInput input) at System.Data.Entity.Internal.LazyInternalContext.InitializeContext() at System.Data.Entity.Internal.InternalContext.Initialize() at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) at System.Data.Entity.Internal.Linq.InternalSet1.Initialize() at System.Data.Entity.Internal.Linq.InternalSet1.GetEnumerator() at System.Data.Entity.Infrastructure.DbQuery1.System.Collections.Generic.IEnumerable.GetEnumerator() at System.Collections.Generic.List1..ctor(IEnumerable1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at TestApplication.MainWindow.Window_Loaded(Object sender, RoutedEventArgs e) in D:RailwayProjectsRelayAnalysisTestApplicationMainWindow.xaml.cs:line 33 InnerException:

推荐答案

我认为外键应该是 Id,而不是 StandardRack_id.此外,您应该使用虚拟,以便能够使用延迟加载.

I think the foreignKey should be Id, not StandardRack_id. Also, you should use virtual, in order to be able to use lazy loading.

这对我有用

using System.ComponentModel.DataAnnotations;
using System.Data.Entity;

namespace Racks
{

    public class StandardRack
    {
        public int Id { get; set; }
        public virtual StandardRelay StandardRelay { get; set; }
    }

    public class StandardRelay
    {
        public int Id { get; set; }

        public int StandardRack_Id { get; set; }

        [ForeignKey("Id")]
        [Required]
        public virtual StandardRack StandardRack { get; set; }
    }

    public class Context : DbContext
    {
        static Context()
        {
            Database.SetInitializer<Context>(null);
        }

        public DbSet<StandardRack> StandardRacks { get; set; }
        public DbSet<StandardRelay> StandardRelays { get; set; }

    }

    class Program
    {
        static void Main(string[] args)
        {
            var context = new Context();
            context.Database.Delete();
            context.Database.Create();

            var standardRack = new StandardRack();
            standardRack.StandardRelay = new StandardRelay();

            context.StandardRacks.Add(standardRack);
            context.SaveChanges();
        }
    }
}

这篇关于实体框架代码优先:使用注解设置一对一的外键关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆