Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# EFCore 2 Fluent API用于构建自定义映射规则_C#_Domain Driven Design_Ef Core 2.0 - Fatal编程技术网

C# EFCore 2 Fluent API用于构建自定义映射规则

C# EFCore 2 Fluent API用于构建自定义映射规则,c#,domain-driven-design,ef-core-2.0,C#,Domain Driven Design,Ef Core 2.0,我遇到了这样一种情况:我试图构建一个与数据库不完全匹配的域模型,并且我很难找到如何使用EFCore构建映射规则 预约域模型 public class Appointment { public string Title { get; set; } public long UserId { get; set; } public string UserFullName { get; set; } public DateTime StartDate { get

我遇到了这样一种情况:我试图构建一个与数据库不完全匹配的域模型,并且我很难找到如何使用EFCore构建映射规则

预约域模型

public class Appointment  
{

    public string Title { get; set; }

    public long UserId { get; set; }

    public string UserFullName { get; set; }

    public DateTime StartDate { get; set; }

    public DateTime EndDate { get; set; }

    public void MyBusinessLogic(){}
}
这是精简版,但要点是我不希望在我的约会模型中将完整的用户对象作为属性,例如:

public User User {get;set;} <== trying to avoid adding this to the class
public用户{get;set;}x.Title)
.IsRequired(正确)
.HasMaxLength(任命常量MaxTitleLength);
builder.Property(x=>x.Description)
.IsRequired(正确)
.HasMaxLength(任命常量MaxDescriptionLength);
builder.HasOne()
.有很多
.HasForeignKey(x=>x.UserId)
.OnDelete(DeleteBehavior.Restrict);
}
}
所以我想弄清楚的是,是否有可能为UserFullName属性构建某种映射规则,通过连接First和Last name列从用户表中读取它的数据,但不应该写入该表

就像使用Automapper这样的工具一样


基本上,我只想对EFCore说,当我查询约会数据时,从用户表中获取UserFullName的值,并连接FirstName和LastName列中的值

您不能直接映射相关实体的属性,但可以通过使用私有属性/字段来避免污染模型的问题

public class Appointment  
{  
    ...
    private User user;  
    public string UserFullName => $"{user.FirstName} {user.LastName}";  
    ...  
}
builder.HasOne(“用户”)
.有很多
.HasForeignKey(x=>x.UserId)
.OnDelete(DeleteBehavior.Restrict);
在构建查询时,不要忘记
。包括(“用户”)

还要注意,DbContext现在正在跟踪此用户,如果您修改它,它的更改将在稍后的
SaveChanges
调用中保存到DB中

public class Appointment  
{  
    ...
    private User user;  
    public string UserFullName => $"{user.FirstName} {user.LastName}";  
    ...  
}
    builder.HasOne<User>("user")
        .WithMany()
        .HasForeignKey(x => x.UserId)
        .OnDelete(DeleteBehavior.Restrict);