Я использую EF 4.1 code first
, и я борюсь с объектом ассоциации и получаю значение, которое было установлено в таблице ассоциаций. Я попытался следить за сообщением: Create code first, many to many, with additional fields in association table.Извлечение значения в таблице ассоциаций в коде Entity Framework сначала
Мои таблицы следующим образом (все они находятся в форме множественного числа):
Таблица: Продукты
Id int
Name varchar(50)
Таблица: Технические характеристики
Id int
Name varchar(50)
Таблица: ProductSpecifications
ProductId int
SpecificationId int
SpecificationValue varchar(50)
Мои связанные классы:
public class Product : IEntity
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<ProductSpecification> ProductSpecifications { get; set; }
}
public class Specification : IEntity
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<ProductSpecification> ProductSpecifications { get; set; }
}
public class ProductSpecification
{
public int ProductId { get; set; }
public virtual Product Product { get; set; }
public int SpecificationId { get; set; }
public virtual Specification Specification { get; set; }
public string SpecificationValue { get; set; }
}
Мой контекст Класс:
public class MyContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Specification> Specifications { get; set; }
public DbSet<ProductSpecification> ProductSpecifications { get; set; }
protected override void OnModelCreating(DbModelBuilder dbModelBuilder)
{
}
}
Мой вместилище метод, где я делаю вызов (не уверен, что это правильно):
public class ProductRepository : IProductRepository
{
MyContext db = new MyContext();
public Product GetById(int id)
{
var product = db.Products
.Where(x => x.Id == id)
.Select(p => new
{
Product = p,
Specifications = p.ProductSpecifications.Select(s => s.Specification)
})
.SingleOrDefault();
return null; // It returns null because I don't know how to return a Product object?
}
}
Здесь вы ошибка, которую я возвращаю:
One or more validation errors were detected during model generation:
System.Data.Edm.EdmEntityType: : EntityType 'ProductSpecification' has no key defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: EntitySet �ProductSpecifications� is based on type �ProductSpecification� that has no keys defined.
Что означает, что ключи не определены? Не будет ли ProductId и SpecificationId отображать идентификатор продукта и идентификатор спецификации соответственно?
Как я могу вернуть один продукт со всеми его спецификациями?