EF5 Code First and RIA Services Silverlight “Object reference not set to an instance of an object” error building client

坚强是说给别人听的谎言 提交于 2020-01-13 10:05:02

问题


I am working on setting up a new project using Code First for entity framework 5 in silverlight using RIA services. I have created a test project due to some issues I have encountered and will post the code below.

Namely, I get an 'Object reference not set to an instance of an object' error anytime I attempt to build the silverlight client project which should generate the client proxy classes.

Just to be clear, this error is not while running or debugging the application, but when building it.

I have isolated that this only happens if I have any navigation properties/Foreign Keys defined on my Code First classes.

Any help tonight would be greatly appreciated.

    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
}

回答1:


Your foreign key fields aren't mapped, thus they can't be interpreted by the proxy code generator (the piece of code called to build your proxy during compilation).
You should put in you DbContext something like

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
      modelBuilder.Entity<Character>()
          .HasRequired(x=> x.Person)
          .WithMany(x=> x.Characters)
          .HasForeignKey(x=> x.PersonId);
 }

also, I suggest you to change your
public virtual List<Character> Characters { get; set; }
to
public virtual ICollection<Character> Characters { get; set; } , because I'm not sure if the proxy generator (and EF too) will map that list correctly.
EDIT:
I'm thinking that the EF Metadataprovider isn't supplying the correct attribute in description.
Put a KeyAttribute over the Character.CharacterId and Person.PersonID, also, add this line over Character.Person

[Association("Character_Person", "PersonId", "PersonId", IsForeignKey = true)]

and this one over Person.Characters

Association("Character_Person", "PersonId", "PersonId")]<br>

EDIT:
After chat with KitKat we finally found the problem. During proxy generation a call to Assembly.GetExportedTypes crashed complainig it need EF 4.1. Simple putting

<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
  </dependentAssembly>
</assemblyBinding>

in the related config did the tricks

Note: at this link ther's blog post from mine that better explains how to deal with EF5 Code first and WCF Ria Services



来源:https://stackoverflow.com/questions/13059127/ef5-code-first-and-ria-services-silverlight-object-reference-not-set-to-an-inst

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!