这是一个基于 Programming Code First EF 的示例。
请看下面的课程。当 PersonRepository 调用实例化并调用 InsertOrUpdate 方法时,返回 Null 值。据我所知,IQuariable 的 FitstOrDefault 不应返回 Null。
这里有什么问题。谢谢您的帮助
public class Person
{
public int PersonId { get; set; }
public int SocialSecurityNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
//public int MyProperty { get; set; }
public List<Lodging> PrimaryContactFor { get; set; }
public List<Lodging> SecondaryContactFor { get; set; }
public PersonPhoto Photo { get; set; }
}
照片课
public class PersonPhoto
{
public int PersonID { get; set; }
public byte[] Photo { get; set; }
public string Caption { get; set; }
public Person PhotoOf { get; set; }
}
DBContext 类
public class DomainContext:DbContext,IDisposable
{
public DomainContext(string connectionString):base(connectionString)
{
}
public DbSet<Person> People { get; set; }
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<PersonPhoto>()
.HasKey(p => p.PersonID);
modelBuilder.Entity<PersonPhoto>()
.HasRequired(p => p.PhotoOf)
.WithRequiredDependent(p => p.Photo);
}
}
存储库类
public class PersonRepository
{
public PersonRepository()
{
}
public void InsertOrUpdate()
{
using( DomainContext ctx = new DomainContext())
{
var person= ctx.People.Include("Photo").FirstOrDefault();
person.FirstName="Pnikey";
if(person.Photo==null)
{
person.Photo= new PersonPhoto{Photo=new byte[]{0}};
}
ctx.SaveChanges();
}
}
}