对于我的作业,我需要使用SQL数据库中的Entity Framework从c#应用程序获取数据。
问题是我不知道我做错了什么。
我的课程:
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;
}
}
}
我的用户类。我使用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();
}
}
我正在搜索并尝试理解它一段时间,但如何将var转换为组织模型?或者我错过了一个重要的代码和平?
答案 0 :(得分:1)
确定。在您的方法中,您希望返回单个Organization
对象:
public static Organisation Find(int id)
但您的LINQ查询实际上返回了一组对象:
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;
}
在这种情况下,您将按主键过滤组织,并且当此查询返回多于1行时不存在任何情况。然后你可以拨打SingleOrDefault()
:
var organisation = (from b in context.Organisations
where b.Id = id
select b).SingleOrDefault();
return organisation;
using (var context = new OrganisationContext())
{
// Query for all blogs with names starting with B
var organisation = context.Organisations.Find(id)
return organisation;
}
EF中实体的一个常见要求是无参数构造函数。因此,您需要删除Organization
类的现有constroctor或添加另一个:
public Organization() { }