我正在使用 RIA 服务在 Silverlight 中使用 Code First 为实体框架 5 设置一个新项目。由于遇到的一些问题,我创建了一个测试项目,并将在下面发布代码。
即,每当我尝试构建应生成客户端代理类的 silverlight 客户端项目时,都会收到“对象引用未设置为对象的实例”错误。
需要明确的是,此错误不是在运行或调试应用程序时出现,而是在构建时出现。
我已经隔离,只有在我的 Code First 类上定义了任何导航属性/外键时才会发生这种情况。
今晚的任何帮助将不胜感激。
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime? BirthDate { get; set; }
public virtual List<Character> Characters { get; set; }
}
public class Character
{
public int CharacterId { get; set; }
public int PersonId { get; set; }
public virtual Person Person { get; set; }
public string CharacterName { get; set; }
}
public class CharacterDbContext : DbContext
{
public DbSet<Person> Persons { get; set; }
public DbSet<Character> Characters { get; set; }
public CharacterDbContext()
{
if (HttpContext.Current == null)
{
Database.SetInitializer<CharacterDbContext>(null);
}
}
}
[EnableClientAccess]
public class CharacterDbService : DbDomainService<CharacterDbContext>
{
#region Basic Methods for Person with the context property of Persons
[Query]
public IQueryable<Person> GetPersons()
{
return DbContext.Persons;
}
[Insert]
public void InsertPerson(Person entity)
{
DbEntityEntry<Person> entityEntry = DbContext.Entry(entity);
if (entityEntry.State != EntityState.Detached)
{
entityEntry.State = EntityState.Added;
}
else
{
DbContext.Persons.Add(entity);
}
}
[Update]
public void UpdatePerson(Person entity)
{
DbContext.Persons.AttachAsModified(entity, ChangeSet.GetOriginal(entity), DbContext);
}
[Delete]
public void DeletePerson(Person entity)
{
DbEntityEntry<Person> entityEntry = DbContext.Entry(entity);
if (entityEntry.State != EntityState.Deleted)
{
entityEntry.State = EntityState.Deleted;
}
else
{
DbContext.Persons.Attach(entity);
DbContext.Persons.Remove(entity);
}
}
#endregion
#region Basic Methods for Character with the context property of Characters
[Query]
public IQueryable<Character> GetCharacters()
{
return DbContext.Characters;
}
[Insert]
public void InsertCharacter(Character entity)
{
DbEntityEntry<Character> entityEntry = DbContext.Entry(entity);
if (entityEntry.State != EntityState.Detached)
{
entityEntry.State = EntityState.Added;
}
else
{
DbContext.Characters.Add(entity);
}
}
[Update]
public void UpdateCharacter(Character entity)
{
DbContext.Characters.AttachAsModified(entity, ChangeSet.GetOriginal(entity), DbContext);
}
[Delete]
public void DeleteCharacter(Character entity)
{
DbEntityEntry<Character> entityEntry = DbContext.Entry(entity);
if (entityEntry.State != EntityState.Deleted)
{
entityEntry.State = EntityState.Deleted;
}
else
{
DbContext.Characters.Attach(entity);
DbContext.Characters.Remove(entity);
}
}
#endregion
}