0

For my homework I need to get the data with a c# application using Entity Framework out of a SQL database.

The problem is that I have no idea what I am doing wrong.

My class:

public class Organisation
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Organisation(int Id, string Name)
    {
        this.Id = Id;
        this.Name = Name;
    }

    public class OrganisationContext : DbContext
    {
        public DbSet<Organisation> Organisations { get; set; }
    }

    public static Organisation Find(int id) {
        using (var context = new OrganisationContext())
        {
            // Query for all blogs with names starting with B 
            var organisation = from b in context.Organisations
                        where b.Id = id
                        select b;
            return organisation;
        }
    }
}

My user class. I use Identity.

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }

    public string Firstname { get; set; }
    public string Interjunction { get; set; }
    public string Lastname { get; set; }
    public int OrganisationId { get; set; }

    public virtual Organisation Organisation
    {
        get
        {
            return Organisation.Find(OrganisationId);
        }
    }  

    public int Role { get; set; }

    public string DisplayName
    {
        get
        {
            string dspFirstname = string.IsNullOrWhiteSpace(this.Firstname) ? "" : this.Firstname;
            string dspInterjunction = string.IsNullOrWhiteSpace(this.Interjunction) ? "" : this.Interjunction + " ";
            string dspLastname = string.IsNullOrWhiteSpace(this.Lastname) ? "" : this.Lastname;

            return string.Format("{0} {1}{2}", dspFirstname, dspInterjunction, dspLastname);
        }
    }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

I am searching and trying to understand it for a while but how do I convert a var to an organisation model? Or am I missing an important peace of code?

2
  • What's wrong with your code now? It looks OK. Also, you can use single DBContext for users and organization if it stores in the same DB. Commented Feb 20, 2016 at 10:54
  • It now says cannot implicitly convert type 'System.Linq.IQueryable<ServerHomeworkWeek3.Models.Organisation>' to 'ServerHomeworkWeek3.Models.Organisation.' An explicit conversion exists (are you missing a cast?) I know it is a lot easyer to place it all in the same table but we need to do this according to the school project Commented Feb 20, 2016 at 11:01

1 Answer 1

1

Ok. In your method you want to return single Organization object:

public static Organisation Find(int id)

But your LINQ query actually returns a collection of objects:

using (var context = new OrganisationContext())
{
    // Query for all blogs with names starting with B 
    var organisation = from b in context.Organisations
                where b.Id = id
                select b;
    return organisation;
}

In this case you are filtering organization by primary key and there is no situation when this query returns more then 1 row. Then you can just call SingleOrDefault():

var organisation = (from b in context.Organisations
                where b.Id = id
                select b).SingleOrDefault();
return organisation;

Also, you can use Find method from DbSet class:

using (var context = new OrganisationContext())
{
    // Query for all blogs with names starting with B 
    var organisation = context.Organisations.Find(id)
    return organisation;
}

One of the common requirements for entities in EF is parameterless constructor. So, you need to remove existed constroctor for Organization class or add another one:

public Organization() { }
Sign up to request clarification or add additional context in comments.

6 Comments

it returns another exception System.Reflection.TargetInvocationException was unhandled by user code maybe you might know why? InnerException: HResult=-2146233079 Message=The class 'ServerHomeworkWeek3.Models.Organisation' has no parameterless constructor. Source=EntityFramework
@StuiterSlurf You need to add a dummy parameterless constructor to Organisation, a'la private Organisation() { }. EF requires one to construct objects from database data.
It's because The class 'ServerHomeworkWeek3.Models.Organisation' has no parameterless constructor. Add default constructor to your entity: public Organisation() { } or delete existed constructor. It's one of the common requirements to your entities in EF.
ok this is a stupid question but why does it need a private empty constructor?
First of all - not private. The second one - it's not stupid question :) OK. When Entity framework retrieves data from database it needs to create new class with retrieved data. EF can't just call constructor with parameters because it can't associate constructor parameters with this data. Then EF always creates new entity with parameterless constructor and then set each property by name. If there is no parameterless constructor then EF can't create new instance of your entity.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.