Reputation: 1511
I wanna know if i can use mongodb like models (model classes) in my project (asp.net mvc 4 c#).
For example:
namespace Demo.Models
{
public class Model1
{
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
}
public class MovieDBContext : DbContext
{
public DbSet<Model1> models { get; set; }
}
}
Let's say this is standard model for mssql database. Can i create models like this to use MongoDB collections, documents? If yes, how? (if you can provide me with link of some examples).
Thanks.
Upvotes: 4
Views: 1348
Reputation: 88
Yes you can use mongodb as model in your project. you just have to define a model class and get the required enetities that you need.But in this you have provide an BsonId
attribute for any object for generating a unique id.
here's is a example from my code just check it out.
public class QuestionAttempt
{
public ObjectId QId { get; set; }
public long UserId { get; set; }
[BsonElement("SN")]
public string SkillName { get; set; }
[BsonElement("IC")]
public bool IsCorrect { get; set; }
}
In my code i have given some objects a smaller name with the [BsonElement()]
attribute for less memory usage.
Upvotes: 2
Reputation: 4817
Yes you can don't forget to add BsonId attribute, because every object has to have his own unique id.
public class Model1
{
[BsonId]
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
}
And example you can find here:
http://www.joe-stevens.com/2011/10/02/a-mongodb-tutorial-using-c-and-asp-net-mvc/
Upvotes: 3