我是Entity框架的新手,我仍然在努力了解如何处理它。 我碰到了一个奇怪的问题。我试图为一个"一个>多个"创建一个客户吸气剂。关系,但由于某种原因,它不起作用,因为我期待。
请查看以下代码:
namespace DigitalCard.Data.Models
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNet.Identity.EntityFramework;
using DigitalCard.Data.Commons.Interfaces;
using DigitalCard.Data.Commons;
using Microsoft.AspNet.Identity;
using System.ComponentModel.DataAnnotations.Schema;
public class User : BasicDbEntry, IUser, IBasicUser
{
public User(string userName, string firstName, string lastName) : this(userName)
{
this.UserName = userName;
this.FirstName = firstName;
this.LastName = lastName;
}
public virtual string PasswordHash { get; set; }
//---> Table Attributes
[Required]
[Index("UserName", 1, IsUnique = true)]
[MaxLength(100)]
public string UserName { get; set; }
[Required]
[MaxLength(100)]
public string FirstName { get; set; }
[Required]
[MaxLength(100)]
public string LastName { get; set; }
[Required]
public int Age { get; set; }
//---> Referances to other tables
public virtual ICollection<Phone> _phones { get; set; }
[NotMapped]
public virtual ICollection<Phone> Phones
{
get { return this._phones == null ? new List<Phone>() : this._phones.Where(a => a.IsDeleted == false).ToList<Phone>(); }
set { this._phones = value; }
}
}
}
这是Phone类:
public class Phone : BasicContact
{
public Phone() : base() { }
// Table Attributes
[Required]
[IsPhoneNumber]
public string Number { get; set; }
}
public class BasicContact : BasicDbEntry
{
public BasicContact()
{
}
// Table Attributes
[Required(ErrorMessage = "Every type of contact should have a Label")]
public string Label { get; set; }
// Reference to other table
public virtual User _user { get; private set; }
[NotMapped]
public virtual User User
{
get { return this._user; }
set { this._user = value; }
}
}
public class BasicDbEntry : IBasicDbEntry
{
public BasicDbEntry()
{
this.Id = Guid.NewGuid().ToString();
this.CreatedOn = new DateTime(1900, 1, 1);
this.DeletedOn = new DateTime(1900, 1, 1);
this.ModifiedOn = new DateTime(1900, 1, 1);
}
[Key]
[Required(ErrorMessage = "Every database item should have an Id")]
public string Id { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime ModifiedOn { get; set; }
public bool IsDeleted { get; set; }
public DateTime? DeletedOn { get; set; }
}
本练习的重点是以某种方式告诉EF只提取未删除的电话号码e.t. &#34; isDelete == false
&#34;当我写UserInstance.Phones
我做错了什么?
答案 0 :(得分:1)
下面的代码看起来就像是要躲避EF。
public virtual ICollection<Phone> _phones { get; set; }
[NotMapped]
public virtual ICollection<Phone> Phones
{
get { return this._phones == null ? new List<Phone>() : this._phones.Where(a => a.IsDeleted == false).ToList<Phone>(); }
set { this._phones = value; }
}
我建议你离开并修改这一行(因为应该这样做,默认为EF)
public virtual ICollection<Phone> Phones { get; set; }
稍后在您的代码中,当您实例化DbContext时,只需为IsDeleted
添加此检查。如果您担心这一点,那对性能来说不是那么大的问题。无论如何,DbContext将在第一个缓存级别的内存中拥有DbSets的完整副本(大约告知)。