Entity framework 将实体属性映射到其他表
我有两个实体:Entity framework 将实体属性映射到其他表,entity-framework,ef-code-first,Entity Framework,Ef Code First,我有两个实体: 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 } } 我的数据库架构
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
列。我需要一种方法来告诉实体框架导航外键,并获取CreatedUserName
属性的UserName
列的值
这可能吗?我不希望产品拥有整个用户实体
谢谢
这可能吗?我不希望产品拥有整个用户实体
否,除非您要为产品执行数据库视图。您尝试映射的对象不再是真实的实体。它更像一个视图模型,为什么不使用投影呢
var productView = context.Products
.Where(p => p.Id == ...)
.Select(p => new ProductView {
Id = p.Id,
Name = p.Name,
CreatedUserName = p.User.UserName
});
这可能吗?我不希望产品拥有整个用户实体
否,除非您要为产品执行数据库视图。您尝试映射的对象不再是真实的实体。它更像一个视图模型,为什么不使用投影呢
var productView = context.Products
.Where(p => p.Id == ...)
.Select(p => new ProductView {
Id = p.Id,
Name = p.Name,
CreatedUserName = p.User.UserName
});
我也在研究同样的事情,发现了一种叫做“实体分割”的技术 因此,根据您的代码,您似乎可以:
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");
});
}
我也在研究同样的事情,发现了一种叫做“实体分割”的技术 因此,根据您的代码,您似乎可以:
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");
});
}
您的意思是外键指向用户表吗?我认为您需要查看的是独立关联,其中您的实体上有导航属性,但外键没有公开。您的意思是外键指向用户表吗?我认为您需要查看的是独立关联,其中您的实体上有导航属性,但外键不公开。