EntityFramework使用导航属性来填充计算属性

时间:2013-04-01 15:07:01

标签: entity-framework ef-code-first asp.net-web-api

基本上我想做的是返回一个只读字符串(用户名),该字符串取决于导航属性User,只是将名字和姓氏连接在一起。

理想情况下,我只是为OwnerUserId分配一个值,然后使用navigation属性检索数据是否可行?我希望尽可能保持模型类的清洁。

有什么想法吗?

POCO模型

namespace Model
{
public class TicketReply
    {

    public int TicketReplyId { get; set; }
    public string Title { get; set; }
    /* ....more.... */

    /* User ID FK */
    public int OwnerUserId { get; set; }
    /* User Navigation property */
    [ForeignKey("OwnerUserId")]
    [IgnoreDataMember]
    public User User { get; set; }

    /* Here is where I am stuck.... */
    public string UserName
    {
        get { return User.FirstName + " " + User.LastName; }
        set { }
    }

    }
}

* 数据库初始化 * - 仅提供一些背景信息

private List<TicketReply> AddReplies(DbContext context)
{
        var replies = new List<TicketReply>
        {
            new TicketReply { TicketReplyId = 1, TicketId = 1, CreatedAt = DateTime.Now, OwnerUserId = 1, Text = "My initial query"},
            new TicketReply { TicketReplyId = 2, TicketId = 1, CreatedAt = DateTime.Now, OwnerUserId = 2, Text = "Test reply."},
            new TicketReply { TicketReplyId = 3, TicketId = 2, CreatedAt = DateTime.Now, OwnerUserId = 1, Text = "Test query"} 
        };
        replies.ForEach(status => context.TicketReplies.Add(status));
        context.SaveChanges();
        return replies;
}

由于 亚瑟

1 个答案:

答案 0 :(得分:0)

大致(并从记忆中打字)
使其成为User的一部分,例如......

public class User
{
    [NotMapped] // or from code  "modelBuilder.Entity<User>().Ignore(x => x.UserName);"
    public string UserName
    // your user name implementation
}
  

你不能只是分配OwnerUserId并期望它工作 - 用户会   加载Ticket时加载。你也不要使用'OwnerUserId'   你的fk-entity - 搜索用户。

您可以使用它来“设置”用户'它指向' - 当您第一次执行'SaveChanges'时它会被保存。

例如......

var user = new User {First = ... Second=...};
db.Tickets.Add(new Ticket{ User = user, ...});
// or...
db.Tickets.Add(new Ticket{ OwnerUserId = ownerid, ...}); // to point to exisitng one you know exists         
db.SaveChanges();
...sometime later on...
var ticket = new Ticket { OwnerUserId = ownerid };
// ticket.User is null - won't work
var ticket = // tickets query // db.Tickets.Where(x => x.TicketId == ticketid).FirstOrDefault();
var username = ticket.User.UserName; // now it works, you have your User loaded

或明确地......

var user = db.Users.Where(x => x.UserId == ownerid).FirstOrDefault();
var username = user.UserName;