An ojective should have one Category(one-to-one),
the objective has Actions and each one of them should have one Action Category(one-to-one) and many Resource Categories(one-to-many).
I don't know how to configure the mapping. Also i'm not sure if my design is correct, how to manage this case properly?
Summary:
I need 3 relationships.
1) one-to-one between Objective and Category on ObjectiveCategoryId property of Objective.
2) one-to-one between ObjectiveAction and Category on ActionCategoryId property of ObjectiveAction.
3) one-to-many between ObjectiveAction and Category on ObjectiveId property of Category.
public class Category {
public int Id { get; set; }
public string Name { get; set; }
}
public class Objective {
private ICollection<DevelopmentObjectiveAction> _actions;
public int Id { get; set; }
public string Name { get; set; }
public int ObjectiveCategoryId { get; set; }
public Category ObjectiveCategory { get; set; }
public ICollection<ObjectiveAction> Actions {
get => _actions ?? (_actions = new List<ObjectiveAction> ());
set => _actions = value;
}
}
public class ObjectiveAction {
private ICollection<Category> _resourceCategories;
public int Id { get; set; }
public string Name { get; set; }
public long ObjectiveId { get; set; }
public long Objective { get; set; }
public int ActionCategoryId { get; set; }
public Category ActionCategory { get; set; }
public ICollection<Category> ResourceCategories {
get => _resourceCategories ?? (_resourceCategories = new List<Category> ());
set => _resourceCategories = value;
}
}
Related
I have two entities connected by a many-to-many relationship.
First class:
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
public List<MovieActor> MovieActor { get; set; }
}
Second class:
public class Actor
{
public int Id { get; set; }
public string Name { get; set; }
public List<MovieActor> MovieActor { get; set; }
}
And relationship (many to many):
public class MovieActor
{
public int MovieId { get; set; }
public Movie Movie { get; set; }
public int ActorId { get; set; }
public Actor Actor { get; set; }
}
I want to write the IEnumerable<Movie> GetMovies(int actorId) method, which takes the actor's id as the parameter. I would like the method to return a list of movies in which an actor with the given Id plays. How can I do that?
You do not need the MovieActor class
Change to:
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
public List<Actor> Actors { get; set; }
}
public class Actor
{
public int Id { get; set; }
public string Name { get; set; }
public List<Movie> Movies { get; set; }
}
Then you can select the Actor and you have the list of Movies as a property on the actor.
so you can do something like this
public IEnumerable<Movie> GetMovies(int actorId)
{
var result = await _context.Actor.Where(x => x.Id == actorId).
Include(x => x.MovieActor).ThenInclude(x => x.Movie).FirstOrDefaultAsync();
var movies = result.MovieActor.select(x => x.Movie).Tolist();
return movies
}
When attempting a straight forward projection using Entity Framework Core and Linq, I am getting an "Argument types do not match" exception.
I have looked into possible causes and have narrowed it down to the Select that is causing the error (see below). There is a GitHub issue describing a similar situation with simple types and optional navigation entities, but none of the suggested solutions have worked for me. It is not a nullable type and I have tried casting or using Value on any child properties. I have also tried setting the relationship to required in the DbContext which isn't exactly ideal.
Here is the Linq query in the repository:
return await _dashboardContext.PresetDashboardConfig
.Where(config => config.DashboardTypeId == dashboardType && config.OrganisationType = organisationType)
.GroupBy(config => config.GroupId)
.Select(config => new DashboardConfigDTO
{
DashboardType = config.First().DashboardTypeId,
OrganisationId = organisationId,
WidgetGroups = config.Select(group => new WidgetGroupDTO
{
Id = group.Id,
Name = group.GroupName,
TabOrder = group.TabOrder,
// Problem Select below:
Widgets = group.Widgets.Select(widget => new WidgetConfigDTO
{
IndicatorId = widget.IndicatorId,
ScopeId = widget.ScopeId.ToString(),
ParentScopeId = widget.ParentScopeId.ToString(),
WidgetType = widget.WidgetType,
WidgetSize = widget.WidgetSize,
Order = widget.Order
})
})
})
.SingleOrDefaultAsync();
And the entities:
public class DashboardConfig
{
public int Id { get; set; }
public int DashboardTypeId { get; set; }
public int OrganisationType {get; set; }
public int GroupId { get; set; }
public string GroupName { get; set; }
public int TabOrder { get; set; }
}
public class PresetDashboardConfig : DashboardConfig
{
public ICollection<PresetWidgetConfig> Widgets { get; set; }
}
public class WidgetConfig
{
public int Id { get; set; }
public int IndicatorId { get; set; }
public long ScopeId { get; set; }
public long? ParentScopeId { get; set; }
public int WidgetType { get; set; }
public int WidgetSize { get; set; }
public int Order { get; set; }
}
public class PresetWidgetConfig : WidgetConfig
{
public int PresetDashboardConfigId { get; set; }
}
And finally, the DbContext ModelBuilder:
modelBuilder.Entity<PresetDashboardConfig>(entity =>
{
entity.Property(e => e.GroupName)
.HasMaxLength(32)
.IsUnicode(false);
entity.HasMany(e => e.Widgets)
.WithOne();
});
Below are the DTO classes as per Henk's comment:
public class DashboardConfigDTO
{
public int DashboardType { get; set; }
public int OrganisationId { get; set; }
public IEnumerable<WidgetGroupDTO> WidgetGroups { get; set; }
}
public class WidgetGroupDTO
{
public int Id { get; set; }
public string Name { get; set; }
public int TabOrder { get; set; }
public IEnumerable<WidgetConfigDTO> Widgets { get; set; }
}
public class WidgetConfigDTO
{
public int IndicatorId { get; set; }
public string ScopeId { get; set; }
public string ParentScopeId { get; set; }
public int WidgetType { get; set; }
public int WidgetSize { get; set; }
public int Order { get; set; }
}
I have this two class
public class Category
{
public int Id{ get; set; }
public string Name { get; set; }
}
public class Filter
{
public int Id{ get; set; }
public string Name { get; set; }
}
And I have another Entity like this
public class Menu
{
public int Id{ get; set; }
public string Name { get; set; }
public MenuType MenuType { get; set; }
}
That the MenuType is enum Like this
public enum MenuType
{
Category = 0,
Filter = 1
}
i want to know in class menu how can store Category OR Filter
i mean Menu have relate with one Category or one Filter , now how can I make this relationship?
and one other thing is maybe MenuType will extende and added some other menutype and thats class.
Is not possible to have a column Foreign Key (FK) that can reference two tables.
A option would be:
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public List<Menu> Menus { get; set; }
}
public class Filter
{
public int Id { get; set; }
public string Name { get; set; }
public List<Menu> Menus { get; set; }
}
public class Menu
{
public int Id { get; set; }
public string Name { get; set; }
public MenuType MenuType { get; set; }
public int? CategoryId { get; set; }
public int? FilterId { get; set; }
public Category Category { get; set; }
public Filter Filter { get; set; }
}
Inside your context:
modelBuilder.Entity<Menu>().HasOne(x => x.Category).WithMany(x => x.Menus).HasForeignKey(x => x.CategoryId);
modelBuilder.Entity<Menu>().HasOne(x => x.Filter).WithMany(x => x.Menus).HasForeignKey(x => x.FilterId);
And based on MenuType, you either use Category or Filter object.
I'm using Entity Framework with a code-first approach
But I get a few errors:
User: FromRole: NavigationProperty 'User' is not valid. Type 'SoteAccount' of FromRole 'User_SoteAccounts_Target' in AssociationType 'User_SoteAccounts' must exactly match with the type 'AllegroAccount' on which this NavigationProperty is declared on.
AllegroAccount_Template_Source: : Multiplicity is not valid in Role 'AllegroAccount_Template_Source' in relationship 'AllegroAccount_Template'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be ''.
SoteAccount_Template_Source: : Multiplicity is not valid in Role 'SoteAccount_Template_Source' in relationship 'SoteAccount_Template'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be ''.
Is it even possible to inherit a class with reference ?
Here are the classes and onModelCreating
[Table("AllegroAccounts")]
public class AllegroAccount : ShopAccountBase
{
public string AllegroLogin { get; set; }
public string AllegroPassword { get; set; }
public string AllegoWebApiKey { get; set; }
public int CountryCode { get; set; }
}
public class ShopAccountBase : AccountBase
{
public int TemplateForeignKey { get; set; }
[ForeignKey("TemplateForeignKey")]
public Template Template { get; set; }
}
public abstract class AccountBase
{
[Key]
public int AccountBaseId { get; set; }
public bool IsActive { get; set; }
public int UserForeignKey { get; set; }
[ForeignKey("UserForeignKey")]
public virtual User User { get; set; }
public bool DaysCountActive { get; set; }
public int DaysCount { get; set; }
}
public class Template
{
public Template()
{
AdditionalServices = new AdditionalServices();
BasicServices = new BasicServices();
TemplatePackages = new ObservableCollection<TemplatePackage>();
}
[Key]
public int TemplateID { get; set; }
public string TemplateName { get; set; }
public TemplateKind? TemplateKind { get; set; }
public CourierFirm? CourierFirm { get; set; }
public int Used { get; set; }
public virtual ICollection<TemplatePackage> TemplatePackages { get; set; }
public string ExternalNumber { get; set; }
public string MPKNumber { get; set; }
public AdditionalServices AdditionalServices { get; set; }
public BasicServices BasicServices { get; set; }
public string Description { get; set; }
[Column(TypeName = "datetime")]
public DateTime? CreationDate { get; set; }
}
public class User
{
public User()
{
DefaultReturnAddress = new Address( );
DefaultSendingAddress = new Address( );
PersonInfoSending = new PersonInfo( );
PersonInfoReturning = new PersonInfo( );
AdditionalServices = new AdditionalServices( );
WayBillLabel = new WaybillLabel( );
Settings = new UserSettings( );
AllegroAccounts = new ObservableCollection<AllegroAccount>();
InpostAccounts = new ObservableCollection<InpostAccount>();
TbaAccounts = new ObservableCollection<TbaAccount>();
TruckerAccounts = new ObservableCollection<TruckerAccount>();
}
[Key]
public int UserId { get; set; }
public byte[] Password { get; set; }
public string Login { get; set; }
public Address DefaultReturnAddress { get; set; }
public Address DefaultSendingAddress { get; set; }
public PersonInfo PersonInfoSending { get; set; }
public PersonInfo PersonInfoReturning { get; set; }
public string MPKnumReturn { get; set; }
public string MPKnumSending { get; set; }
public AdditionalServices AdditionalServices { get; set; }
public float MaxLength { get; set; }
public float MaxWidth { get; set; }
public float MaxHeight { get; set; }
public float MaxWeight { get; set; }
public int FileTemplateId { get; set; }
public string CollectiveShipmentFilePath { get; set; }
private PermissionFlags _permissions;
public PermissionFlags Permissions
{
get { return _permissions; }
set
{
if (_permissions.HasFlag(value)) { _permissions &= ~value; }
else {
_permissions |= value;
}
}
}
public TemplatingMethod TemplatingMethod { get; set; }
public UserSettings Settings { get; set; }
public WaybillLabel WayBillLabel { get; }
public ICollection<AllegroAccount> AllegroAccounts { get; set; }
public ICollection<SoteAccount> SoteAccounts { get; set; }
public ICollection<InpostAccount> InpostAccounts { get; set; }
public ICollection<TruckerAccount> TruckerAccounts { get; set; }
public ICollection<TbaAccount> TbaAccounts { get; set; }
// this is the right property to use for modifying the collection
public ICollection<string> AvailableMpksCollection { get; set; }
// this is computed property for Entity Framework only, because it cannot store a collection of primitive type
public string AvailableMpksString
{
get { return AvailableMpksCollection != null ? string.Join(",", AvailableMpksCollection) : null; }
set {
AvailableMpksCollection = !string.IsNullOrEmpty(value) ? value.Split(',').ToList( ) : new List<string>( );
}
}
}
modelBuilder.Entity<AllegroAccount>().HasOptional(account => account.Template).WithOptionalDependent();
modelBuilder.Entity<User>()
.HasMany<AllegroAccount>(u => u.AllegroAccounts)
.WithOptional(acc => acc.User)
.HasForeignKey(acc => acc.UserForeignKey);
modelBuilder.Entity<SoteAccount>().HasOptional(account => account.Template).WithOptionalDependent();
modelBuilder.Entity<User>()
.HasMany<SoteAccount>(u => u.SoteAccounts)
.WithOptional(acc => acc.User)
.HasForeignKey(acc => acc.UserForeignKey);
Does anyone know if it's possible or should I keep it flat and don't inherit it like that? I'm asking because that inheritance would fit nicely with my generic repository model
This is likely because you are defining [ForeignKey] attributes AND configuring the foreign key in the fluent configuration.
You've defined links between (AllegroAccount and User) and (SoteAccount and User) in the fluent configuration, when your AccountBase already has this defined using the [ForeignKey].
The same thing is most likely true for your Template links - the relationship is defined at the ShopAccountBase level by the [ForeignKey] attribute - you don't need to redefine it for the inherited classes in the fluent config.
Try removing all of your modelBuilder fluent configuration entries - it should still work by inheriting the relationships.
I've three entities, say Parent, Child & GrandChild. This GrandChild has got three lists(a,b & c).
How to retrive all these lists using "Include" in Entity Framework?
I can retrive one list like this: Include("Parent.Child.GrandChild.a"),
but when I add another Include like : Include("Parent.Child.GrandChild.b"), it throws an error.
How will i retrive all these lists in a single query?
My code is as follows:
objUserNew = objContaxt.ContextRegistration
.Include("listing.postlist.commentslist")
.Include("listing.postlist.taglist")
.Include("listing.postlist.knocklist")
.FirstOrDefault(x => x.id == objUser.id);
public class registration
{
public int id { get; set; }
public string firstname { get; set; }
public forgtPass forgtPass { get; set; }
public List<listing> listing { get; set; }
}
public class listing
{
public int id { get; set; }
public string address { get; set; }
public List<post> postlist { get; set; }
}
public class post
{
public int id { get; set; }
public string imgUrl { get; set; }
public List<tag> taglist { get; set; }
public List<comments> commentslist { get; set; }
public List<knoqs> knoqs { get; set; }
}
public class tag
{
public string name { get; set; }
}
public class comments
{
public int id { get; set; }
public string comment { get; set; }
public status status { get; set; }
}
public class knoqs
{
public int id { get; set; }
public virtual int registration_id { get; set; }
[ForeignKey("registration_id")] public registration registration { get; set; }
public status status { get; set; }
}