Entity Framework 4 - отношения «один ко многим» с представлением CTP5 (сначала код) - PullRequest
2 голосов
/ 08 марта 2011

Я пытаюсь отобразить взаимосвязь 1-M между двумя объектами, где первая обычно отображается в таблице, а вторая берется из вида.

Участвующие лица:

public class Institute
{
    public int Id { get; set; }
    public string Name { get; set; }
    //...
    public virtual ICollection<Text> Texts { get; set; }
}

public class Text
{
    public int InstituteId { get; set; }
    public int TextId { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
    public bool IsRequired { get; set; }
    public int? MaxLength { get; set; }
}

Соответствующий код сопоставления:

private void MapInstituteText(EntityTypeConfiguration<InstituteText> text)
{
    //From a view
    text.HasKey(i => i.InstituteId)
        .ToTable("vwInstituteTexts");

    text.Property(i => i.InstituteId)
        .HasColumnName("FKInstituteID")
        .IsRequired();

    text.Property(i => i.TextPropertyId)
        .HasColumnName("FKTextPropertyID")
        .IsRequired();

    text.Property(i => i.Name)
        .HasColumnName("Name")
        .IsRequired();

    text.Property(i => i.Value)
        .HasColumnName("Value");

    text.Property(i => i.IsRequired)
        .IsRequired();

    text.Property(i => i.MaxLength);
}

private void MapInstitute(EntityTypeConfiguration<Institute> institute)
{
    institute.HasKey(i => i.Id)
        .ToTable("Institutes");

    institute.Property(i => i.Id)
        .HasColumnName("ID")
        .IsRequired();

    institute.Property(i => i.Name)
        .HasColumnName("Name")
        .HasMaxLength(128)
        .IsRequired();

    institute
        .HasMany(i => i.Texts)
        .WithRequired()
        .HasForeignKey(t => t.InstituteId);
}

Проблема в том, что модель не проверена:

Метод инициализации Studentum.Core.Tests.InstituteTests.Initialize бросил исключение. System.TypeInitializationException: System.TypeInitializationException: Инициализатор типа для 'Studentum.Core.FluentCoreRepositoryFactory' бросил исключение. ---> System.Data.Entity.ModelConfiguration.ModelValidationException: Одна или несколько ошибок проверки были обнаружено при генерации модели:

System.Data.Edm.EdmAssociationEnd:: Кратность не действительна в роли 'Institute_InnerInstituteTexts_Target' в отношениях 'Institute_InnerInstituteTexts'. Поскольку зависимая роль относится к ключевые свойства, верхняя граница кратность зависимой роли должно быть 1. (имена исключений могут не совпадать точно, потому что я воссоздал часть кода специально для этого поста)

Если я уберу ".HasForeignKey (t => t.InstituteId);" сгенерированный запрос содержит ссылку на поле с именем InstituteId1, которого нет в запрашиваемом представлении

exec sp_executesql N'SELECT 
[Extent1].[FKInstituteID] AS [FKInstituteID], 
[Extent1].[FKTextPropertyID] AS [FKTextPropertyID], 
[Extent1].[Name] AS [Name], 
[Extent1].[Value] AS [Value], 
[Extent1].[IsRequired] AS [IsRequired], 
[Extent1].[MaxLength] AS [MaxLength], 
[Extent1].[InstituteId1] AS [InstituteId1]
FROM [institute].[vwInstituteTexts] AS [Extent1]
WHERE [Extent1].[InstituteId1] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=1360

Есть предложения? Благодаря.

1 Ответ

3 голосов
/ 08 марта 2011

Судя по всему, у вашего View нет необходимых ключей.Попробуйте изменить

text.HasKey(i => i.InstituteId)
        .ToTable("vwInstituteTexts");

на


text.HasKey(i => new {i.InstituteId, i.TextId}).ToTable("vwInstituteTexts")

, это также поможет распознать связь и ключ TextId.

...