How to track what View is generated - asp.net-mvc

I am currently working on a simple comments system.
I have a table that should store comments by following model:
public class Comments
{
[Key]
public int Id { get; set; }
[DataType(DataType.MultilineText)]
public string Text { get; set; }
public DateTime DateCreated { get; set; }
public int FromUserId { get; set; }
public int ToUserId { get; set; }
}
Comments are being written from one user to another on his UserPage.
I get userId from db, looking for id that corresponds my User.Identity.Name (name of authorized user) and pass it to FromUserId.
The question is How can I track on whoose page user is writing comment, in order to pass this to ToUserId.
UserPage is being created dynamically from db.

Related

ASP.NET MVC EF 6: define a lookup table/model

i am trying to define a database model in code-first to see and display which user is assigned as a specialist for the record data.
I have a very simple model for the user:
public class User
{
public int ID { get; set; }
public string userName { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
....
}
Next I have defined two (simple) models which define the data that can be edited by the user and the specialist should be assigned to using a dropdownlist:
public class Order
{
public int ID { get; set; }
public string orderNumber { get; set; }
public int specialistID { get; set; }
public virtual User specialist{ get; set; }
}
public class Part
{
public int ID { get; set; }
public string partNumber { get; set; }
public string description { get; set; }
public int specialistID { get; set; }
public virtual User specialist{ get; set; }
}
What kind of relation between the models can be used without having a navigation property for each table in the User model?
Do I need to use additional tables to define the relationship: User.Id-Order.specialistID and the relationship: User.Id-Part.specialistID ?
Is there a smarter way out-of-the-box by Entity Framework?
Many thanks for your answers.
Pascal
By default when you add forign-key constraint to the many-to-one table the Entity Framework add virtual property to the entity class and virtual ICollection to the User.

display current user data in MVC

In MVC i want to authenticate users,they must not be able to see other user data when logged on. Users must be able to CRUD their own data only. I have created two model:
public class User
{
public int id { get; set; }
public string Username { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public List<Product> Products { get; set; }
}
public class Product
{
public int productId { get; set; }
public string productName { get; set; }
public double productPrice { get; set; }
public User Users { get; set; }
}
And i have product controller, where i want to authenticate users from CRUD other users data.
You can make your code to perform CRUD operations on only the products available for logged in user.
Use below scenario for your requirement.
public class User
{
public int id { get; set; }
public string Username { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public List<Product> Products {
get{
//get all products from database/storage for this user. for ex: I have called a method to get products
//you can filter products related to this user by sending this user id to database or using code like below
//Writing this code/logic in controller would be preferable
return GetAllProducts().Where(p => p.Users.id == this.id).ToList();
}
set;
}
}
Agree with Rajesh, I would recommend you use Current User's data and filter Rajesh you showed. Current User's Data may include Id of current logged user. If you use cookies to keep user's session, you can retrieve his Id from cookies in controller or filter attribute: HttpContext.Current.Request.Cookies["auth_cookie"].

How to associate model data with a user in ASP.NET MVC4?

Is there a built-in way of associating persistent model data with an authenticated user in MVC4, or are you supposed to provide your own implementation?
The MSDN tutorials I've read don't suggest how to do it, but I've seen a WebSecurity.CurrentUserId property I could store. For example, a model for a site that allows the user to upload photos:
public class Photo
{
public int Id { get; set; }
public int UserID { get; set; } // Controller sets WebSecurity.CurrentUserId?
public DateTime Created { get; set; }
...
}
Or is there an "MVC way"?
can you not use something like this:
public class Photo
{
public int Id { get; set; }
public int UserID { get; set; }
public DateTime Created { get; set; }
public UserProfile user {get;set;}
...
}
public class UserProfile
{
public int UserID { get; set; }
}

Navigation property of entity is not loading

I am building a reservation system. I have users in roles('admin', 'client', 'employee', 'student').
Each reservation must be associated with a user of role client, it might be assigned to user of role employee and might also be assigned to user of role student.
So in my reservation class I have properties of type User and I have marked them with [ForeignKey("AnytypeId")] attribute to hint EF for relations.
I have seen code like this at http://blog.stevensanderson.com/2011/01/28/mvcscaffolding-one-to-many-relationships/
public class Reservation
{
public int ReservationID
{
get;
set;
}
[Required(ErrorMessage="Please provide a valid date")]
public DateTime ReservationDate
{
get;
set;
}
public DateTime ReservationEnd { get; set; }
public DateTime EntryDate
{
get;
set;
}
public DateTime UpdatedOn
{
get;
set;
}
public decimal Ammount
{
get;
set;
}
public decimal? Discount { get; set; }
[DataType(DataType.MultilineText)]
public string ServiceDetails { get; set; }
[DataType(DataType.MultilineText)]
public string Remarks { get; set; }
public String PaymentMethod { get; set; }
public string VoucherNumber { get; set; }
public int ServiceID
{
get;
set;
}
public virtual Service Service
{
get;
set;
}
public string EmployeeID { get; set; }
[ForeignKey("EmployeeID")]
public virtual User Employee { get; set; }
public string ClientID { get; set; }
[ForeignKey("ClientID")]
public virtual User Client { get; set; }
public string StudentID { get; set; }
[ForeignKey("StudentID")]
public virtual User Student { get; set; }
}
public class ReservationMap : EntityTypeConfiguration<Reservation>
{
public ReservationMap()
{
this.HasOptional(r => r.Client).WithMany().WillCascadeOnDelete(true);
this.HasOptional(r => r.Employee).WithMany().WillCascadeOnDelete(false);
this.HasOptional(r=>r.Student).WithMany().WillCascadeOnDelete(false);
}
}
Now as I run my mvc3 EF code first app database created for me on the fly with following ERD and edmx model.
Now few problems that I am having:
1. When I am listing all the users of role clients in view their reservation property is showing always 0 even if their are reservations available in database. I don't know why this collection property marked with virtual is not loading??
Please I am stuck with this help me out here this is the last thing remaining.
There are couple of problems in your model. You have configured the one to many relationship in such a way that the many end(Reservations property) is excluded from the mapping. Hence the Reservations will not be loaded by EF.
The other problem is if you are going to map the Reservations property as the many end of the relationship, what will be the navigational property? is it Employee, Client, Student? Because only one of these properties can participate in the relationship with Reservations property.
It is not clear as to how these relationships should be modeled by your description. One way would be to have 3 collection properties.
public class ReservationMap : EntityTypeConfiguration<Reservation>
{
public ReservationMap()
{
HasOptional(r => r.Client).WithMany(u => u.ClientReservations).WillCascadeOnDelete(true);
HasOptional(r => r.Employee).WithMany(u => u.EmployeeReservations).WillCascadeOnDelete(false);
HasOptional(r=>r.Student).WithMany(u => u.StudentReservations).WillCascadeOnDelete(false);
}
}

Entity Framework 4 CTP 5 POCO - Many-to-many or Lookup table?

I'm building a personal blog app with Entity Framework 4 CTP 5 POCO only, where a Post can have many Tags and a Tag can be in many Posts. My question is whether to build a many-to-many model, or to have a lookup table.
At first I was trying to use many-to-many, but I don't know how to do insertion, each time a new post is posted (with many tags selected), I'm not sure what to do so that the tags should be associated with the post (and wouldn't insert a new tag if the tag name already exists.)
I then try to build a Lookup table like so:
Post
public class Post
{
public int Id { get; set; }
[Required]
[StringLength(512, ErrorMessage = "Title can't exceed 512 characters")]
public string Title { get; set; }
[Required]
[AllowHtml]
public string Content { get; set; }
public string FriendlyUrl { get; set; }
public DateTime PostedDate { get; set; }
public bool IsActive { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
public virtual ICollection<PostTagLookup> PostTagLookups { get; set; }
}
Tag
public class Tag
{
public int Id { get; set; }
[Required]
[StringLength(25, ErrorMessage = "Tag name can't exceed 25 characters.")]
public string Name { get; set; }
public string FriendlyName { get; set; }
public virtual ICollection<PostTagLookup> PostTagLookups { get; set; }
}
PostTagsLookup
public class PostTagLookup
{
public int PostId { get; set; }
public int TagId { get; set; }
}
The problem is I'm not sure how EF are going to handle lookup table (how will I get the Tags of a Post, or a collection of the Posts when I select a Tag). And with the code below, I got an error saying PostTagLookup doesn't have an Id key:
var getPosts = _post.GetLatestPosts(3).ToList();
var posts = from post in getPosts
select new PostModel
{
Id = post.Id,
Title = post.Title,
Content = post.Content,
FriendlyUrl = post.FriendlyUrl,
PostedDate = post.PostedDate,
IsActive = post.IsActive,
NumberOfComments = post.Comments.Count(),
PostTags = post.PostTagLookups.Where(p => p.PostId == post.Id).ToList()
};
Any suggestion on how to accomplish this task? Thank you very much!
I think your model should work as-is with a slight tweak: add an ID column/field to the PostTagLookup entity.
public class PostTagLookup
{
[Key]
[DatabaseGenerated(DatabaseGenerationOption.Identity)]
public int PostTagLookupId { get; set; }
//etc.
}
However, I'm not sure why you wouldn't want EF to handle the underlying many-to-many on it's own. When you have a new Post object, for example, all you have to do is add any associated Tags to the instantiated Post's Tags collection before calling SaveChanges() on your context. Did this not work for you?
I've struggled with it for the past couple days and decided to go with the Lookup table as intended, and in the Lookup table, also have references to Post and Tag model as such:
public class PostTagLookup
{
public int Id { get; set; }
public int PostId { get; set; }
public int TagId { get; set; }
public virtual Post Post { get; set; }
public virtual Tag Tag { get; set; }
}
Might not be the best way but it's working :) Thanks all for looking.

Resources