EF 4.1 Code First:为什么EF没有设置此导航属性?

时间:2011-08-15 00:05:06

标签: entity-framework-4.1

这是一个示例场景,说明了我遇到的问题。

以下是在SQL 2008中生成数据库的数据库脚本:

USE [master]
GO

/****** Object:  Database [EFTesting]    Script Date: 08/15/2011 09:56:33 ******/
CREATE DATABASE [EFTesting] ON  PRIMARY 
( NAME = N'EFTesting', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\EFTesting.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'EFTesting_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\EFTesting_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO

ALTER DATABASE [EFTesting] SET COMPATIBILITY_LEVEL = 100
GO

USE [EFTesting]
GO

/****** Object:  Table [dbo].[Schedule]    Script Date: 08/15/2011 09:45:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Schedule](
    [ScheduleID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](50) NOT NULL,
    [Version] [timestamp] NOT NULL,
 CONSTRAINT [PK_Schedule] PRIMARY KEY CLUSTERED 
(
    [ScheduleID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

/****** Object:  Table [dbo].[Customer]    Script Date: 08/15/2011 09:45:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Customer](
    [CustomerID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](50) NOT NULL,
    [ScheduleID] [int] NOT NULL,
    [Version] [timestamp] NOT NULL,
 CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED 
(
    [CustomerID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

/****** Object:  ForeignKey [FK_Customer_Schedule]    Script Date: 08/15/2011 09:45:53 ******/
ALTER TABLE [dbo].[Customer]  WITH CHECK ADD  CONSTRAINT [FK_Customer_Schedule] FOREIGN KEY([ScheduleID])
REFERENCES [dbo].[Schedule] ([ScheduleID])
GO
ALTER TABLE [dbo].[Customer] CHECK CONSTRAINT [FK_Customer_Schedule]
GO

以下是模型,上下文和测试工具的C#代码:

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

namespace Tester
{
    public class Context : DbContext
    {
        public Context(string connectionString) : base(connectionString)
        {
            Configuration.LazyLoadingEnabled = false;
            Configuration.ProxyCreationEnabled = false;
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // Customer
            modelBuilder.Entity<Customer>()
                .HasKey(c => c.ID)
                .Property(c => c.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).HasColumnName("CustomerID");

            modelBuilder.Entity<Customer>()
                .Property(c => c.Version).IsConcurrencyToken();

            modelBuilder.Entity<Customer>()
                .HasRequired(c => c.Schedule);

            modelBuilder.Entity<Customer>()
                .ToTable("Customer");

            // Schedule
            modelBuilder.Entity<Schedule>()
                .HasKey(s => s.ID)
                .Property(s => s.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).HasColumnName("ScheduleID");

            modelBuilder.Entity<Schedule>()
                .Property(s => s.Version).IsConcurrencyToken();

            modelBuilder.Entity<Schedule>()
                .ToTable("Schedule");
        }
    }

    public class Customer
    {
        public Customer()
        {
            Schedule = new Schedule();
        }

        public int ID { get; set; }

        public string Name { get; set; }

        public int ScheduleID { get; set; }

        public Schedule Schedule { get; set; }

        public byte[] Version { get; set; }
    }

    public class Schedule
    {
        public int ID { get; set; }

        public string Name { get; set; }

        public byte[] Version { get; set; }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            // create new customer / schedule
            var context = new Context(@"Data Source=.\SQLEXPRESS;Initial Catalog=EFTesting;Integrated Security=True;MultipleActiveResultSets=True");
            var customer = new Customer
            {
                Name = "CUSTOMER",
                Schedule = new Schedule
                {
                    Name = "SCHEDULE"
                }
            };

            context.Set<Customer>().Add(customer);
            context.SaveChanges();

            // pull new customer
            context = new Context(@"Data Source=.\SQLEXPRESS;Initial Catalog=EFTesting;Integrated Security=True;MultipleActiveResultSets=True");
            var result = context.Set<Customer>().Include(c => c.Schedule).Single(c => c.ID == customer.ID);

            // this succeeds
            Debug.Assert(result.ScheduleID == customer.Schedule.ID);

            // this fails - Schedule is not set to database version, is left as new version from constructor
            Debug.Assert(result.Schedule.ID == customer.Schedule.ID);
        }
    }
}

您可以看到在Customer构造函数中创建了一个默认的Schedule实例,因此它永远不会是空引用。但问题是,当EF从数据库加载客户时,如果它不为空,则根本不设置Schedule引用。

这会导致外键属性ScheduleID与导航属性不同步,并且稍后会导致异常。

任何人都可以解释为什么EF会这样做以及是否有办法在不改变模型设计的情况下解决它?对我来说这感觉就像是一个错误,即使这是设计上的错误,因为模型没有被框架保持同步。

1 个答案:

答案 0 :(得分:1)

我对你的问题没有很好的答案,但无论如何我都会试一试。

基本上,您无法在构造函数中初始化Schedule属性。通过这样做,EF认为该属性已被修改(设置为新值)并且不会尝试覆盖它。实际上,如果在代码中的断言之前添加另一个context.SaveChanges(),您将看到EF尝试插入您在构造函数中创建的新Schedule实体。

我可以建议的唯一解决方法是在类外部手动初始化属性,或者更好的是,创建一个备用Customer构造函数并使默认值为protected或private:

public class Customer
{
    public Customer(string name)
    {
        Name = name;
        Schedule = new Schedule();
    }

    protected Customer() { }

    public int ID { get; set; }
    public string Name { get; set; }
    public int ScheduleID { get; set; }
    public Schedule Schedule { get; set; }
    public byte[] Version { get; set; }
}

EF将使用默认构造函数,但您可以在代码中使用另一个。

我明白你的意思,这似乎是一个错误,但我也理解为什么EF做它做的事情......我想我就是这样做的。

无论如何,祝你好运!