In my project there is one to may relationship with two table(questions and asnwars). but when creating question no need to add answar but in my problem getting this error
Object reference not set to an instance of an object.
how can I solve this? is there any wrong thing in my code
this is the code what I tried.
public class QuestionDTO
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public string question { get; set; }
public int votes { get; set; }
public ApplicationUser starter { get; set; }
public virtual ICollection<VegCategoryDTO> tags { get; set; }
public ICollection<AnswerDTO> answers { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<QuestionDTO>().ToTable("tblQuestion");
modelBuilder.Entity<AnswerDTO>()
.HasRequired<QuestionDTO>(s => s.Question)
.WithMany(g => g.answers)
.HasForeignKey<int>(s => s.QuestionId)
.WillCascadeOnDelete();
}
}
public class QuestionController : ApiController
{
[AllowAnonymous]
public QuestionVM Post(QuestionVM model)
{
//if (!ModelState.IsValid)
//{
// return null;
//}
QuestionDTO dto = new QuestionDTO();
using (Db db = new Db())
{
dto.Id = model.Id;
dto.Title = model.Title;
dto.votes = model.votes;
dto.question = model.question;
ApplicationUser currentUser = (new ApplicationDbContext()).Users.FirstOrDefault(x => x.Id == userId);
dto.starter = currentUser;
dto.tags = model.tags;
dto.answers = model.answers;
db.Questions.Add(dto);
db.SaveChanges();
}
//_DbContext.SaveChanges();
return new QuestionVM(dto);
}
}
public class Db : DbContext
{
public DbSet<VegCategoryDTO> VegCategories { get; set; }
public DbSet<QuestionDTO> Questions { get; set; }
public DbSet<AnswerDTO> Answers { get; set; }
public DbSet<ApplicationUser> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<QuestionDTO>()
.HasMany<VegCategoryDTO>(s => s.tags)
.WithMany(c => c.Questions)
.Map(cs =>
{
cs.MapLeftKey("QuestiontRefId");
cs.MapRightKey("VegCategoryRefId");
cs.ToTable("QuestiontVegCategory");
});
modelBuilder.Entity<AnswerDTO>()
.HasRequired<QuestionDTO>(s => s.Question)
.WithMany(g => g.answers)
.HasForeignKey<int>(s => s.QuestionId)
.WillCascadeOnDelete();
}
}
I been breaking my head for hours trying to find out why my navigation property is coming back null for 0 to many scenario. For 1 to 1 it works just fine.
These are my entities:
public class Barber: BaseEntity
{
public string Street1 { get; set; }
public string Street2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public int? AppointmentId { get; set; }
public int? UserId { get; set; }
public virtual ICollection<Users> Users { get; set; }
public Barber()
{
}
}
public class Users: BaseEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public bool IsBarber { get; set; }
public int? BarberId { get; set; }
public string FacebookToken { get; set; }
public DateTime? CreatedOn { get; set;}
public virtual Barber Barber { get; set; }
/// <summary>
/// default constructor
/// </summary>
public Users() { }
}
my mapping is as follow:
for Barber:
public BarberMapping()
{
ToTable("Barber");
HasKey(p => p.Id);
Property(p => p.Street1).HasColumnName("Street1");
Property(p => p.Street2).HasColumnName("Street2");
Property(p => p.City).HasColumnName("City");
Property(p => p.State).HasColumnName("State");
Property(p => p.PostalCode).HasColumnName("PostalCode");
Property(p => p.AppointmentId).HasColumnName("AppointmentId");
Property(p => p.UserId).HasColumnName("UserId");
HasOptional(p => p.Users)
.WithMany()
.HasForeignKey(p => p.UserId);
}
}
for User:
public UserMapping()
{
ToTable("Users");
HasKey(p => p.Id);
Property(p => p.FirstName);
Property(p => p.LastName );
Property(p => p.Password);
Property(p => p.Email);
Property(p => p.CreatedOn);
Property(p => p.FacebookToken);
Property(p => p.IsBarber);
}
Finally i'm calling my data like this:
_userRepository.All.Where(p => p.Id == id).Include(p => p.Barber).FirstOrDefault();
When the query comes back I get everything except the Barber property which comes back as null. Anything i'm missing to make this relationShip work?
I'm using EF 6.1.3 with mySQL 6.9 on visual studio for mac.
I am having an issue using an AutoMapper (version 5.1.1) projection combined with a Linq OrderBy Child property expression. I am using Entity Framework Core (version 1.0.0). I am getting the following error:
"must be reducible node"
My DTO objects are as follows
public class OrganizationViewModel
{
public virtual int Id { get; set; }
[Display(Name = "Organization Name")]
public virtual string Name { get; set; }
public virtual bool Active { get; set; }
public virtual int OrganizationGroupId { get; set; }
public virtual string OrganizationGroupName { get; set; }
public virtual int StrategyId { get; set; }
public virtual string StrategyName { get; set; }
public virtual OrganizationGroupViewModel OrganizationGroup { get; set; }
}
public class OrganizationGroupViewModel
{
public virtual int Id { get; set; }
[Display(Name = "Organization Group Name")]
public virtual string Name { get; set; }
public virtual bool Active { get; set; }
}
My corresponding entity models are as follows:
public class Organization
{
public int Id { get; set; }
public string Name { get; set; }
public string TimeZone { get; set; }
public bool Active { get; set; }
//FKs
public int OrganizationGroupId { get; set; }
public int StrategyId { get; set; }
//Navigation
public virtual OrganizationGroup OrganizationGroup { get; set; }
public virtual Strategy Strategy { get; set; }
[JsonIgnore]
public virtual List<AppointmentReminder> AppointmentReminders { get; set; }
}
public class OrganizationGroup
{
public int Id { get; set; }
public string Name { get; set; }
public bool Active { get; set; }
public virtual List<Organization> Organizations { get; set; }
}
My AutoMapper profiles are as follows:
public class OrganizationMapperProfile : Profile
{
public OrganizationMapperProfile()
{
CreateMap<Task<Organization>, Task<OrganizationViewModel>>();
CreateMap<Organization, OrganizationViewModel>()
.ForMember(dest => dest.OrganizationGroupName, opt => opt.MapFrom(src => src.OrganizationGroup.Name));
CreateMap<OrganizationInput, Organization>()
.ForMember(x => x.Id, opt => opt.Ignore());
}
}
public class OrganizationGroupMapperProfile : Profile
{
public OrganizationGroupMapperProfile()
{
CreateMap<Task<OrganizationGroup>, Task<OrganizationGroupViewModel>>();
CreateMap<OrganizationGroup, OrganizationGroupViewModel>();
CreateMap<OrganizationGroupInput, OrganizationGroup>()
.ForMember(x => x.Id, opt => opt.Ignore());
}
}
When I run the following statements I am able to run and get results from the first 2 statements:
var tmp = await _context.Organizations.Include(x => x.OrganizationGroup).OrderBy(x => x.OrganizationGroup.Name).ToListAsync();
var tmp4 = await _context.Organizations.Include(x => x.OrganizationGroup).OrderBy("OrganizationGroup.Name").ToListAsync();
But when I add the ProjectTo I get the error listed above:
var tmp5 = await _context.Organizations.Include(x => x.OrganizationGroup).OrderBy(x => x.OrganizationGroup.Name).ProjectTo<OrganizationViewModel>().ToListAsync();
var tmp6 = await _context.Organizations.Include(x => x.OrganizationGroup).OrderBy("OrganizationGroup.Name").ProjectTo<OrganizationViewModel>().ToListAsync();
As some additional information, I am able to OrderBy with Projections working on properties of the parent class, such as:
var tmp7 = await _context.Organizations.Include(x => x.OrganizationGroup).OrderBy(x => x.Name).ProjectTo<OrganizationViewModel>().ToListAsync();
var tmp8 = await _context.Organizations.Include(x => x.OrganizationGroup).OrderBy("Name").ProjectTo<OrganizationViewModel>().ToListAsync();
Anyone run into this issue before? Looks like I'm trying to do something that is otherwise not supported, is that by design? Thanks for any help/insight.
Looks like the problem is caused by the OrganizationGroup property of the OrganizationViewModel class - AutoMapper generates a null check which EF Core doesn't like in the combination with your OrderBy (I guess just one of the many bugs currently in EF Core). It can easily be reproduced by the following simple manual projection query:
var tmp5a = _context.Organizations
.OrderBy(x => x.OrganizationGroup.Name)
.Select(e => new OrganizationViewModel
{
Id = e.Id,
OrganizationGroup = e.OrganizationGroup != null ? new OrganizationGroupViewModel
{
Id = e.OrganizationGroup.Id,
Name = e.OrganizationGroup.Name,
Active = e.OrganizationGroup.Active,
} : null,
})
.ToList();
To fix the issue, configure AutoMapper to not generate null check for that property as follows:
CreateMap<Organization, OrganizationViewModel>()
.ForMember(dest => dest.OrganizationGroup, opt => opt.AllowNull())
.ForMember(dest => dest.OrganizationGroupName, opt => opt.MapFrom(src => src.OrganizationGroup.Name));
I have the following scenario that is giving me a hard time:
public class SegUser
{
public string IdUser { get; set; }
public List<SegRol> SegRoles { get; set; }
public virtual List<SegApps> Apps{ get; set; }
}
public class SegRole
{
public virtual int IdRole { get; set; }
public virtual List<SegUer> SegUsers { get; set; }
public virtual List<SegApp> Apps { get; set; }
}
public class SegApp
{
public virtual int IdApp{ get; set; }
public virtual List<SegUser> Users { get; set; }
public virtual List<SegRole> Roles { get; set; }
}
In my database I have those 3 tables and an extra table with 3 PKs (one for each entity) to establish the relationship between those 3 entities.
How can I achieve the mapping with Entity Framework 5 fluent API.
I've already tried:
private void MapSegUser()
{
//mapping of another fields
entityConfiguration
.HasMany(x => x.SegRoles)
.WithMany(x => x.SegUsers)
.Map(mc =>
{
mc.MapLeftKey("id_role");
mc.MapRightKey("id_user");
mc.ToTable("seg_users_roles");
});
entityConfiguration
.HasMany(x => x.Apps)
.WithMany(x => x.Users)
.Map(mc =>
{
mc.MapLeftKey("id_app");
mc.MapRightKey("id_user");
mc.ToTable("seg_users_roles_apps");
});
}
private void MapSegApp()
{
//mapping of another fields
entityConfiguration
.HasMany(x => x.Users)
.WithMany(x => x.Apps)
.Map(mc =>
{
mc.MapLeftKey("id_user");
mc.MapRightKey("id_app");
mc.ToTable("seg_users_roles_apps");
});
}
private void MapSegRole()
{
//mapping of another fields
entityConfiguration
.HasMany(x => x.SegUsers)
.WithMany(x => x.SegRoles)
.Map(mc =>
{
mc.MapLeftKey("id_user");
mc.MapRightKey("id_role");
mc.ToTable("seg_users_roles");
});
}
Following is a save routine on existing record. What's wrong with this? I'm using independent association
There's no error emitted, however, the Country_CountryId field on Person table didn't change, everything else are properly persisted. What's wrong on the following code/approach?
public JsonResult SaveUpdate(Person p)
{
p.Country = new Country { CountryId = new Guid("EF0CD98E-7138-4757-866E-ADC3C8D216DA") };
using (var db = new TheDbContext())
{
db.Entry(p).State = System.Data.EntityState.Modified;
db.SaveChanges();
}
}
Here's my mapper:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Person>().HasRequired(x => x.Country)
.WithMany(x => x.Persons)
.Map(x => x.MapKey("Country_CountryId"));
modelBuilder.Entity<Person>().Property(x => x.RowVersion).IsRowVersion();
modelBuilder.Entity<Country>().HasKey(x => x.CountryId);
}
Here's my models:
public class Country
{
public virtual Guid CountryId { get; set; }
public virtual string CountryCode { get; set; }
public virtual string CountryName { get; set; }
public virtual IList<Person> Persons { get; set; }
}
public class Person
{
public virtual Guid PersonId { get; set; }
public virtual string Username { get; set; }
public virtual string Firstname { get; set; }
public virtual string Lastname { get; set; }
public virtual byte[] RowVersion { get; set; }
public virtual Country Country { get; set; }
}
Use this instead and it will work:
public JsonResult SaveUpdate(Person p)
{
var country = new Country { CountryId = new Guid("EF0CD98E-7138-4757-866E-ADC3C8D216DA") };
using (var db = new TheDbContext())
{
db.People.Attach(p);
db.Countries.Attach(country);
db.Entry(p).State = System.Data.EntityState.Modified;
p.Country = country;
db.SaveChanges();
}
}
Independent associations require special care because each association itself has its own state which must be configured.