Entityframework:启用延时加载的主意事项(只为强化记忆)
Check List
- 无参的、高于私有访问级别的构造方法(经常忘记)。
- 非封闭的类(默认的非封闭的)。
- DbContext 配置要开启(默认是开启的)。
因为我喜欢将类型设置为封闭的,提供有参数的构造方法,尽可能的低的访问级别,而这些原则和延时加载的原则刚好相反,因此写下来强化一下记忆。
示例
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 using Happy.Archetype; 8 using Happy.Domain; 9 using Happy.Cms.Domain.Shares; 10 11 namespace Happy.Cms.Domain.Articles 12 { 13 [DomainModel, Moment] 14 public class Article : AggregateRoot<Guid> 15 { 16 private ICollection<AssignedTag> _assignedTags = new List<AssignedTag>(); 17 18 protected Article() 19 { 20 } 21 22 public Article(Guid id) 23 : base(id) 24 { 25 this.SettingInfo = new SettingInfo(); 26 this.ImageInfo = new ImageInfo(); 27 this.SeoInfo = new SeoInfo(); 28 } 29 30 public string Title { get; set; } 31 32 public Guid CategoryId { get; set; } 33 34 public string Author { get; set; } 35 36 public ImageInfo ImageInfo { get; private set; } 37 38 public SettingInfo SettingInfo { get; private set; } 39 40 public virtual ICollection<AssignedTag> AssignedTags 41 { 42 get { return _assignedTags; } 43 protected set { _assignedTags = value; } 44 } 45 46 public string Content { get; set; } 47 48 public SeoInfo SeoInfo { get; private set; } 49 50 public void AssignTags(IEnumerable<Guid> tagIds) 51 { 52 tagIds = tagIds ?? Enumerable.Empty<Guid>(); 53 54 var oldAssignedTagIds = this.AssignedTags.Select(x => x.TagId).ToList(); 55 var addedTagIds = tagIds.Except(oldAssignedTagIds); 56 var removedTagIds = oldAssignedTagIds.Except(tagIds); 57 58 foreach (var addedTagId in addedTagIds) 59 { 60 this.AssignedTags.Add(new AssignedTag(Guid.NewGuid(), addedTagId)); 61 } 62 63 foreach (var removedTagId in removedTagIds) 64 { 65 this.AssignedTags.Remove(this.AssignedTags.First(x => x.TagId == removedTagId)); 66 } 67 } 68 } 69 }