2012-12-03 36 views
1

我有两个实体:映射的实体属性不同的表

public class User 
{ 
    public int Id { get; set; } 
    public string UserName { get; set; } 
} 

public class Product 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string CreatedUserName { get; set } 
} 

我的数据库架构包含在Products表的外键指着Products表中的列Id。我需要一种方法告诉Entity Framework导航外键,并获取CreatedUserName属性的UserName列的值。

这可能吗?我不希望产品具有整个用户实体。

谢谢!

+0

你的意思外键指向用户表?我认为你需要看的是独立的关联,你在你的实体上有导航属性,但外键没有公开。 – Pawel

回答

1

这可能吗?我不希望产品具有整个用户实体。

否,除非您想为您的产品执行数据库视图。你试图映射的不再是真实的实体。它更像是一个视图模型,为什么不使用投影?

var productView = context.Products 
         .Where(p => p.Id == ...) 
         .Select(p => new ProductView { 
          Id = p.Id, 
          Name = p.Name, 
          CreatedUserName = p.User.UserName 
         }); 
3

我一直在寻找到同样的事情,发现了一个被称为“实体分割” http://www.deliveron.com/blog/post/Entity-Splitting-in-Code-First-Entity-Framework.aspx

所以技术基础上的代码,它看起来像你可以这样做:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity() 
     // Map to the Product table 
     .Map(map => 
     { 
      map.Properties(p => new { 
       p.Id, 
       p.Name 
      }); 

      map.ToTable("Product"); 
     }) 
     // Map to the User table 
     .Map(map => 
     { 
      map.Properties(p => new { 
       p.CreatedUserName 
      }); 

      map.ToTable("User"); 
     }); 
} 
相关问题