How to make ICollection<Child Entities> Required. How - entity-framework-4.1

Here is my Master Entity who will contains a list of Language
public partial class WebSite
{
public WebSite()
{
this.WebSiteLanguages = new HashSet<WebSiteLanguage>();
}
public int Id { get; set; }
public Nullable<int> WLUserID { get; set; }
public string DomainName { get; set; }
public Nullable<bool> IsActive { get; set; }
//[Required]
public virtual ICollection<WebSiteLanguage> WebSiteLanguages { get; set; }
}
My WebSiteLanguage Child class is
public partial class WebSiteLanguage
{
public int Id { get; set; }
public string LanguageName { get; set; }
public Nullable<int> WebSiteID { get; set; }
public bool IsDefault { get; set; }
public virtual WebSite WebSite { get; set; }
}
In my View, I can Add many language as I want within an ajax call.
My Question is :
Is it possible to make the
public virtual ICollection WebSiteLanguages { get;
set; }
Required. The Website Entity is not valid if there is no WebSiteLanguage created.
Thanks a lot.

As per post http://blogs.msdn.com/b/adonet/archive/2011/05/27/ef-4-1-validation.aspx navigation properties are excluded from facet validation "as you could set the associated FK value and the navigation property would be set on SaveChanges()". To validate that a navigation property is not null you can:
create a custom attribute that validates it (be it on the type or on the property)
implement IValidatableObject interface that does the above
override DbContext.ValidateEntity protected method so that it validates that the property is not null and if this is the case calls base.ValidateEntity() to validate other properties (see this for more details: http://blogs.msdn.com/b/adonet/archive/2010/12/15/ef-feature-ctp5-validation.aspx)
The 3rd solution seems to be the cleanest.

Related

Ignoring fields without JsonProperty attribute [duplicate]

The JsonIgnore attribute can be used to ignore certain properties in serialization. I was wondering if it is possible to do the opposite of that? So a JsonSerializer would ignore every property EXCEPT when there is a special attribute on it?
Yes there is. When you mark your class with [JsonObjectAttribute] and pass the MemberSerialization.OptIn parameter, member serialization is opt-in. Then mark your members with [JsonProperty] to include them for serialization.
[JsonObject(MemberSerialization.OptIn)]
public class Person
{
[JsonProperty]
public string Name { get; set; }
// not serialized because mode is opt-in
public string Department { get; set; }
}
An alternative to MemberSerialization.OptIn is using DataContract/DataMember attributes:
[DataContract]
public class Computer
{
// included in JSON
[DataMember]
public string Name { get; set; }
[DataMember]
public decimal SalePrice { get; set; }
// ignored
public string Manufacture { get; set; }
public int StockCount { get; set; }
public decimal WholeSalePrice { get; set; }
public DateTime NextShipmentDate { get; set; }
}
Source: http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size

Populate DropDown from database in an edit view using MVC4

I am new to MVC and trying to populate a dropdown list in the "create" view which is generated from a view model, but it returns with an error saying object reference is not an instance of an object. below is my code :
Controller Code:
public ActionResult Create()
{
return View(new AddRecipeViewModel());
}
Model Code:
public class DifficultyLevel
{
[Key]
public int Id { get; set; }
public string Difficulty { get; set; }
}
public class AddRecipeViewModel
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<RecipeReview> Reviews { get; set; }
public virtual IEnumerable<DifficultyLevel> Difficulty { get; set; }
}
View:
<div>
<select>
#foreach (var item in Model.Difficulty)
{
<option>#item.Difficulty</option>
}
</select>
</div>
Is there an easy workaround this ? as I will be adding more drop downs in this as I go along.
Thanks,
Vishal
not sure if you need to use virtual in your view models.. that's usually only for the entity models. but anyway, try adding a constructor to AddRecipeViewModel and set the collections equal to empty lists so they won't be null.
public class AddRecipeViewModel
{
public AddRecipeViewModel()
{
Reviews = new List<RecipeReview>();
Difficulty = new List<DifficultyLevel>();
}
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<RecipeReview> Reviews { get; set; }
public virtual IEnumerable<DifficultyLevel> Difficulty { get; set; }
}

EF Problems with Navigation Properties and Mapping

At start i wanted to mention that i've been fighting this thing for a few days and tried many of the answers more or less related to this problem. Yet I could not resolve it.
I have two classes that represent tables in a DB. These are the existing tables used by legacy application and I cannot change them.
Message can have multiple MessageRecipients.
Environment: MVC3, EF4.1
Classes are:
public class Message
{
[ForeignKey("MessageReciepients")]
public virtual int MessageID { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime Recieved { get; set; }
[ForeignKey("User")]
public int AuthorUserID { get; set; }
//P\\ Navigation properties
public virtual IList<MessageRecipient> MessageReciepients { get; set; }
public virtual User User { get; set; }
}
public class MessageRecipient
{
//[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int MessageID { get; set; }
public int UserID { get; set; }
public bool Read { get; set; }
public bool Important { get; set; }
public bool Deleted { get; set; }
public bool Destroyed { get; set; }
//P\\ Navigation Properties
public virtual User User { get; set; }
}
The error I have is:
The foreign key component 'MessageID' is not a declared property on
type 'MessageRecipient'. Verify that it has not been explicitly
excluded from the model and that it is a valid primitive property.
How to correctly map these classes, relationships to load the recipients of a message?
I can add that the navigation property User works correctly for a Message and loads a User's data correctly.
I'm not too experienced with .NET and I learn while doing this.
I tried some EF API config to map these i tried swearing at it, curse it, and been close to cry and pray at the same time. No Joy!!
I would really appreciate the help.
It turned out that the problem was with the composite key that i needed to use and it all could be solved with some attributes:
This is how it looks now:
public class Message
{
public int MessageID { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime Recieved { get; set; }
[ForeignKey("User")]
public int AuthorUserID { get; set; }
//P\\ Navigation properties
public virtual ICollection<MessageRecipient> MessageRecipients { get; set; }
public virtual User User { get; set; }
}
public class MessageRecipient
{
[Key, Column(Order=0), ForeignKey("User")]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int UserID { get; set; }
[Key, Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int MessageID { get; set; }
public bool Read { get; set; }
public bool Important { get; set; }
public bool Deleted { get; set; }
public bool Destroyed { get; set; }
//P\\ Navigation Properties
public virtual User User { get; set; }
}
fill in the missing properties:
public class Message
{
public int MessageID { get; set; }
}
public class MessageRecipient
{
public int MessageID { get; set; }
[ForeignKey("MessageID")]
public Message Message { get; set; }
}

Code First Object not properly instantiating

I have a class department inheriting from activeentity
public class ActiveEntity : Entity, IActive
{
public ActiveEntity()
{
IsActive = true;
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid Id { get; set; }
public bool IsActive { get; set; }
[Timestamp, ScaffoldColumn(false), DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Computed)]
public Byte[] Timestamp { get; set; }
[ScaffoldColumn(false)]
public string CreationUserId { get; set; }
[ScaffoldColumn(false)]
public string LastModifiedUserId { get; set; }
}
public class Department:ActiveEntity
{
public Department()
{
this.Address = new DepartmentAddress();
}
[StringLength(9),MinLength(9),MaxLength(9)]
public string Name { get; set; }
public Guid ManagerId { get; set; }
[UIHint("AjaxDropdown")]
public User Manager { get; set; }
public Guid? AddressId { get; set; }
public DepartmentAddress Address { get; set; }
public ICollection<OverheadRate> OverheadRates { get; set; }
}
I am just using annotations no Fluent API. The data saves to the data Sql Server 2008 just fine however the address object never gets instantiated, even though I have the context use the include
return c.Set<Department>().Include(d => d.Address).Include(d => d.Manager).Where(predicate);
The data is returned I run sql profiler and then run the query it returns the correct data.
Any thoughts or suggestions?
Remove instantiating the address (this.Address = new DepartmentAddress();) in the Department constructor. Instantiating navigation references in the default constructor is evil and has nasty side effects like these:
What would cause the Entity Framework to save an unloaded (but lazy loadable) reference over existing data?
EF 4.1 Code First: Why is EF not setting this navigation property?

Mapping complex tree object using fluent mappings in EF 4.1?

I need some assistance with how to properly mapping this structure in EF 4.1:
public class Menu: Entity
{
public string Title { get; set; }
public virtual ICollection<MenuItem> MenuItems { get; set; }
}
public class MenuItem: Entity
{
public string Icon { get; set; }
public string Text { get; set; }
public string Action { get; set; }
public string Controller { get; set; }
public string Parameters { get; set; }
public virtual MenuItemType Type { get; set; }
public virtual Guid? ContextMenuId { get; set; }
public virtual Menu ContextMenu { get; set; }
public virtual Guid? ParentMenuItemId { get; set; }
public virtual MenuItem ParentMenuItem { get; set; }
public virtual ICollection<MenuItem> ChildMenuItems { get; set; }
}
The Entity base class has the ID for the enitties and I also have a base mapping class that builds the mappings for the key. Here is what I have so far for the MenuItem class:
public class MenuItemMapping : EntityConfiguration<MenuItem>
{
public MenuItemMapping()
{
HasOptional(mi => mi.ParentMenuItem).WithMany(p => p.ChildMenuItems).HasForeignKey(mi => mi.ParentMenuItemId).WillCascadeOnDelete(false);
HasOptional(mi => mi.ContextMenu).WithMany().HasForeignKey(mi => mi.ContextMenuId).WillCascadeOnDelete(false);
}
}
My concern is in the ContextMenu because it is a Menu type and not sure the best way to handle this type o mapping.
Update
Well, I added an additional mapping for the Menu (in a MenuMapping class similar to the above mapping class) for the collection of Menuitems and it seems to be OK, but I'd still like to know if what I am doing is correct.
Apparently, my mappings were fine. I thought I would have issues with circular references.