Search Results

Search found 48396 results on 1936 pages for 'first person shooter'.

Page 6/1936 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • EF Code First to SQL Azure

    - by Predrag Pejic
    I am using EF Code First to create a database on local .\SQLEXPRESS. Among others. I have these 2 classes: public class Shop { public int ShopID { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "You must enter a name!")] [MaxLength(25, ErrorMessage = "Name must be 25 characters or less")] public string Name { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "You must enter an address!")] [MaxLength(30, ErrorMessage = "Address must be 30 characters or less")] public string Address { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "You must enter a valid city name!")] [MaxLength(30, ErrorMessage = "City name must be 30 characters or less")] public string City { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "You must enter a phone number!")] [MaxLength(14, ErrorMessage = "Phone number must be 14 characters or less")] public string Phone { get; set; } [MaxLength(100, ErrorMessage = "Description must be 50 characters or less")] public string Description { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "You must enter a WorkTime!")] public DateTime WorkTimeBegin { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "You must enter a WorkTime!")] public DateTime WorkTimeEnd { get; set; } public DateTime? SaturdayWorkTimeBegin { get; set; } public DateTime? SaturdayWorkTimeEnd { get; set; } public DateTime? SundayWorkTimeBegin { get; set; } public DateTime? SundayWorkTimeEnd { get; set; } public int ShoppingPlaceID { get; set; } public virtual ShoppingPlace ShoppingPlace { get; set; } public virtual ICollection<Category> Categories { get; set; } } public class ShoppingPlace { [Key] public int ShopingplaceID { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "You must enter a name!")] [MaxLength(25, ErrorMessage = "Name must be 25 characters or less")] public string Name { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "You must enter an address!")] [MaxLength(50, ErrorMessage = "Address must be 50 characters or less")] public string Address { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "You must enter a city name!")] [MaxLength(30, ErrorMessage = "City must be 30 characters or less")] public string City { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "You must enter a valid phone number!")] [MaxLength(14, ErrorMessage = "Phone number must be 14 characters or less")] public string Phone { get; set; } public int ShoppingCenterID { get; set; } public virtual ShoppingCenter ShoppingCenter { get; set; } public virtual ICollection<Shop> Shops { get; set; } } and a method in DbContext: modelBuilder.Entity<Item>() .HasRequired(p => p.Category) .WithMany(a => a.Items) .HasForeignKey(a => a.CategoryID) .WillCascadeOnDelete(false); modelBuilder.Entity<Category>() .HasRequired(a => a.Shop) .WithMany(a => a.Categories) .HasForeignKey(a => a.ShopID) .WillCascadeOnDelete(false); modelBuilder.Entity<Shop>() .HasOptional(a => a.ShoppingPlace) .WithMany(a => a.Shops) .HasForeignKey(a => a.ShoppingPlaceID) .WillCascadeOnDelete(false); modelBuilder.Entity<ShoppingPlace>() .HasOptional(a => a.ShoppingCenter) .WithMany(a => a.ShoppingPlaces) .HasForeignKey(a => a.ShoppingCenterID) .WillCascadeOnDelete(false); Why I can't create Shop without creating and populating ShopingPlace. How to achieve that? EDIT: Tried with: modelBuilder.Entity<Shop>() .HasOptional(a => a.ShoppingPlace) .WithOptionalPrincipal(); modelBuilder.Entity<ShoppingPlace>() .HasOptional(a => a.ShoppingCenter) .WithOptionalPrincipal(); and it passed, but what is the difference? And why in SQL Server i am allowed to see ShoppingPlaceID and ShoppingPlace_ShopingPlaceID when in the case of Item and Category i see only one?

    Read the article

  • How to select the first property with unknown name and first item from array in JSON

    - by Oscar Godson
    I actually have two questions, both are probably simple, but for some odd reason I cant figure it out... I've worked with JSON 100s of times before too! but here is the JSON in question: {"69256":{ "streaminfo":{ "stream_ID":"1025", "sourceowner_ID":"2", "sourceowner_avatar":"http:\/\/content.nozzlmedia.com\/images\/sourceowner_avatar2.jpg", "sourceownertype_ID":"1", "stream_name":"Twitter", "streamtype":"Social media" "appsarray":[] }, "item":{ "headline":"Charboy", "main_image":"http:\/\/content.nozzlmedia.com\/images\/author_avatar173212.jpg", "summary":"ate a tomato and avocado for dinner...", "nozzl_captured":"2010-05-12 23:02:12", "geoarray":[{ "state":"OR", "county":"Multnomah", "city":"Portland", "neighborhood":"Downtown", "zip":"97205", "street":"462 SW 11th Ave", "latitude":"45.5219", "longitude":"-122.682" }], "full_content":"ate a tomato and avocado for dinner tonight. such tasty foods. just enjoyable.", "body_text":"ate a tomato and avocado for dinner tonight. such tasty foods. just enjoyable.", "author_name":"Charboy", "author_avatar":"http:\/\/content.nozzlmedia.com\/images\/author_avatar173212.jpg", "fulltext_url":"http:\/\/twitter.com\/charboy\/statuses\/13889868936", "leftovers":{ "twitter_id":"tag:search.twitter.com,2005:13889868936", "date":"2010-05-13T02:59:59Z", "location":"iPhone: 45.521866,-122.682262" }, "wordarray":{ "0":"ate", "1":"tomato", "2":"avocado", "3":"dinner", "4":"tonight", "5":"tasty", "6":"foods", "7":"just", "8":"enjoyable", "9":"Charboy", "11":"Twitter", "13":"state:OR", "14":"county:Multnomah, OR", "15":"city:Portland, OR", "16":"neighborhood:Downtown", "17":"zip:97205" } } } } Question 1: How do I loop through each item (69256) when the number is random? e.g. item 1 is 123, item2 is 646? Like, for example, a normal JSON feed would have something like: {'item':{'blah':'lorem'},'item':{'blah':'ipsum'}} the JS would be like console.log(item.blah) to return lorem then ipsum in a loop How do I do it when i dont know the first item of the object? Question 2: How do I select items from the geoarray object? I tried: json.test.item.geoarray.latitude and json.test.item.geoarray['latitude']

    Read the article

  • Skype will not send/recieve messages to specific person (they will LAG)

    - by iElectric
    There is a similar question, but I tried changing audio settings. I'm using Ubuntu 9.04 and sometimes when talking to specific person it just doesn't send messages or receive them. It may even show that person as offline for few seconds (even if she/he is not). That may not depend on the other side, because it happened on Windows and Ubuntu box. There is a possiblity it's not really limited to skype and it's more of a wider problem, I'm not sure.

    Read the article

  • My first c# app and first null object exception

    - by Fresheyeball
    Total noob here. This is my first c# attempt, its a console application that simulates a drinking game called 'Left Right Center'. In the console I receive the following: CONSOLE Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object at LeftRightCenter.MainClass.Main (System.String[] args) [0x00038] in /Users/apple/Projects/LearningC/LearningC/Main.cs:80 [ERROR] FATAL UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object at LeftRightCenter.MainClass.Main (System.String[] args) [0x00038] in /Users/apple/Projects/LearningC/LearningC/Main.cs:80 C# using System; namespace LeftRightCenter { class Player { //fields private int _quarters = 4; public int Quarters { get{ return _quarters; } set{ _quarters += value; } } public Player (string name) { } } class Dice { Random random = new Random(); public int Roll () { random = new Random (); int diceSide; diceSide = random.Next (0, 6); diceSide = (diceSide > 2) ? 3 : diceSide; return diceSide; } } class MainClass { static int activePlayer = 0; static int theCup = 0; static Player[] thePlayers = { new Player ("Jessica"), new Player ("Isaac"), new Player ("Ed"), new Player ("Bella"), new Player ("Elisa"), new Player ("Fake RedHead"), new Player ("Linda"), new Player ("MJ"), new Player ("Irene"), new Player("Devin") }; static Dice[] theDice = new Dice[2]; private static void MoveQuarter (int direction) { int numberOfPlayers = thePlayers.Length - 1; switch (direction) { case 0: thePlayers [activePlayer].Quarters = -1; theCup++; break; case 1: thePlayers [activePlayer].Quarters = -1; int leftPlayer = (activePlayer == 0) ? numberOfPlayers : activePlayer - 1; thePlayers [leftPlayer].Quarters = +1; break; case 2: thePlayers [activePlayer].Quarters = -1; int rightPlayer = (activePlayer == numberOfPlayers) ? 0 : activePlayer + 1; thePlayers [rightPlayer].Quarters = +1; break; } } public static void Main (string[] args) { int cupEndPoint = thePlayers.Length * 4 - 1; while (theCup < cupEndPoint) { foreach (Dice rattle in theDice) { if (thePlayers [activePlayer].Quarters > 0) { MoveQuarter (rattle.Roll ()); // this line seems to be the problem } } Console.WriteLine ("{0} Quarters In the Cup", theCup); } } } } I have no idea what the problem is or why, and my googling have proven more use confusing than helpful.

    Read the article

  • Difference between Breadth First Search, and Iterative deepening

    - by theraven
    I understand BFS, and DFS, but for the life of me cannot figure out the difference between iterative deepening and BFS. Apparently Iterative deepening has the same memory usage as DFS, but I am unable to see how this is possible, as it just keeps expanding like BFS. If anyone can clarify that would be awesome. tree to work on if required: A / \ B C / / \ D E F

    Read the article

  • Test-First development tool for SQL Server 2005?

    - by Jeff Jones
    For several years I have been using a testing tool called qmTest that allows me to do test-driven database development for some Firebird databases. I write a test for a new feature (table, trigger, stored procedure, etc.) until it fails, then modify the database until the test passes. If necessary, I do more work on the test until it fails again, then modify the database until the test passes. Once the test for the feature is complete and passes 100% of the time, I save it in a suite of other tests for the database. Before moving on to another test or a deployment, I run all the tests as a suite to make sure nothing is broken. Tests can have dependencies on other tests, and the results are recorded and displayed in a browser. Nothing new here, I am sure. Our shop is aiming toward standardizing on MSSQLServer and I want to use the same procedure for developing our databases. Does anyone know of tools that allow or encourage this kind of development? I believe the Team System does, but we do not own that at this point, and probably will not for some time. I am not opposed to scripting, but would welcome a more graphical environment. Any suggestions?

    Read the article

  • Question on First Order Logic formula

    - by none
    Hi, Can someone validate the following. I am supposed to 'write a formula asserting that for every number there's a unique next number...true for integers for instance' L(x,y) means x is smaller than y the intended Domain is the Integer numbers Can I give ∀x ∀y [ x<y ⇒ ( ∃z : z<x ∨ y<z ) ] Thanks

    Read the article

  • Code First CTP4 Error Mapper

    - by user506062
    Why my type always returns 0? public class PartiesConfiguracao : EntityConfiguration<Parties> { public PartiesConfiguracao() { MapHierarchy() .Case<Parties>(parties => new { PartiesID = parties.ID, ShipInstructionID = parties.ShipInstruction.ID, ContactID = parties.Contact.ID, parties.Name, Type = 0, parties.CNPJ, parties.Address }) .Case<Shipper>(parties => new { Type = 1 }) .Case<Consignee>(parties => new { Type = 2 }) .Case<Notify>(parties => new { Type = 3 }) .Case<Forwarder>(parties => new { Type = 4 }) .ToTable("si_Parties"); } }

    Read the article

  • Accessing a Class Member from a First-Class Function

    - by dbyrne
    I have a case class which takes a list of functions: case class A(q:Double, r:Double, s:Double, l:List[(Double)=>Double]) I have over 20 functions defined. Some of these functions have their own parameters, and some of them also use the q, r, and s values from the case class. Two examples are: def f1(w:Double) = (d:Double) => math.sin(d) * w def f2(w:Double, q:Double) = (d:Double) => d * q * w The problem is that I then need to reference q, r, and s twice when instantiating the case class: A(0.5, 1.0, 2.0, List(f1(3.0), f2(4.0, 0.5))) //0.5 is referenced twice I would like to be able to instantiate the class like this: A(0.5, 1.0, 2.0, List(f1(3.0), f2(4.0))) //f2 already knows about q! What is the best technique to accomplish this? Can I define my functions in a trait that the case class extends? EDIT: The real world application has 7 members, not 3. Only a small number of the functions need access to the members. Most of the functions don't care about them.

    Read the article

  • EF4 Code-First CTP5 Many-to-one

    - by Kevin McKelvin
    I've been trying to get EF4 CTP5 to play nice with an existing database, but struggling with some basic mapping issues. I have two model classes so far: public class Job { [Key, Column(Order = 0)] public int JobNumber { get; set; } [Key, Column(Order = 1)] public int VersionNumber { get; set; } public virtual User OwnedBy { get; set; } } and [Table("Usernames")] public class User { [Key] public string Username { get; set; } public string EmailAddress { get; set; } public bool IsAdministrator { get; set; } } And I have my DbContext class exposing those as IDbSet I can query my users, but as soon as I added the OwnedBy field to the Job class I began getting this error in all my tests for the Jobs: Invalid column name 'UserUsername'. I want this to behave like NHibernate's many-to-one, whereas I think EF4 is treating it as a complex type. How should this be done?

    Read the article

  • Save VM properties with EF code first

    - by Julien
    I thought this would be simple but can't find any good examples. public Class BookVm : ImplementsPropertyChanged { public int BookId {get;set;} private bool _favorite; public bool Favorite { get { return _favorite; } set { _favorite = value; OnPropertyChanged("Favorite"); MyDbContext.SaveChanges() // this does not work } } Then in my XAML bound to Book <CheckBox Content="Favorite" IsChecked="{Binding Favorite}" /> How and when do I call SaveChanges() on my DatabaseContext? I don't want to implement a save button. If I intercept the PropertyChange event and call SaveChanges, nothing seems to happen. My object is modified in memory but the database does not see a change. My BookVm class is created on application startup like so: foreach (var book in MyDbContext.Books) Books.Add(book); Where Books is an ObservableCollection<Book> in my MainWindowVm

    Read the article

  • What are the complications involved in this startup:Payments through authorization of fingerprints?

    - by jim859
    I want to make a mobile application where by people can send payments by authorization of finger prints. An email id will be registered and their finger print(unique for everyone) will be stored on our server.Person A and Person B are already registered and have installed the app.A and B deposit some money through our app from their credit card. When a person(Person A) want to send money to other people(person B), person B will ask person A to authorize his/her finger print on person B's mobile.The finger print will be retrieved from our servers and the payment will be made to person B. Person A will open the app (later or at that time) and confirm that yes he/she has authorized his/her finger print for the transaction.If person A has actually done the transaction,no problem.If person A has unknowingly or forcibly and opts that he/she has not authorized his/her finger print,money will be deducted from person B's account. What are the problems/vulnerabilities here,how can it be solved. Any other ways you can suggest to facilitate the transaction

    Read the article

  • Top Down bounds of vision

    - by Rorrik
    Obviously in a first person view point the player sees only what's in front of them (with the exception of radars and rearview mirrors, etc). My game has a top down perspective, but I still want to limit what the character sees based on their facing. I've already worked out having objects obstruct vision, but there are two other factors that I worry would be disorienting and want to do right. I want the player to have reduced peripheral vision and very little view behind them. The assumption is he can turn his head and so see fairly well out to the sides, but hardly at all behind without turning the whole body. How do I make it clear you are not seeing behind you? I want the map to turn so the player is always facing up. Part of the game is to experience kind of a maze and the player should be able to lose track of North. How can I turn the map rather than the player avatar without causing confusion?

    Read the article

  • Code First entity framework connection string

    - by Suneel Dixit
    I have 3 class projects in my solutions. 1. MVC4 project 2. Domain 3. Tests In the MVC4 project I have added a web.config file with the connection string as <add name="EfDbContext" connectionString="Data Source=.;Initial Catalog=SportsStore;Integrated Security=true;" providerName="System.Data.SqlClient"/> I have a class by name EfDbContext in Domain project which inherits DbContext. When I view the website in browser, I get the server not found error. I debugged the EfDbContext class and found that the Database.Connection.ConnectionString is set to \SqlExpress with database as EfDbContext. Why is that?

    Read the article

  • Retrieving only the first record or record at a certain index in LINQ

    - by vik20000in
    While working with data it’s not always required that we fetch all the records. Many a times we only need to fetch the first record, or some records in some index, in the record set. With LINQ we can get the desired record very easily with the help of the provided element operators. Simple get the first record. If you want only the first record in record set we can use the first method [Note that this can also be done easily done with the help of the take method by providing the value as one].     List<Product> products = GetProductList();      Product product12 = (         from prod in products         where prod.ProductID == 12         select prod)         .First();   We can also very easily put some condition on which first record to be fetched.     string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };     string startsWithO = strings.First(s => s[0] == 'o');  In the above example the result would be “one” because that is the first record starting with “o”.  Also the fact that there will be chances that there are no value returned in the result set. When we know such possibilities we can use the FirstorDefault() method to return the first record or incase there are no records get the default value.        int[] numbers = {};     int firstNumOrDefault = numbers.FirstOrDefault();  In case we do not want the first record but the second or the third or any other later record then we can use the ElementAt() method. In the ElementAt() method we need to pass the index number for which we want the record and we will receive the result for that element.      int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };      int fourthLowNum = (         from num in numbers         where num > 5         select num )         .ElementAt(1); Vikram

    Read the article

  • Automatically capitalize first letter of first word in a new sentence in LaTeX

    - by Tom Hagen
    I know one of LaTeX's bragging points is that it doesn't have this Microsoftish behavior. Nevertheless, it's sometimes useful. LaTeX already adds an extra space after you type a (non-backslashed) period, so it should be possible to make it automatically capitalize the following letter as well. Is there an obvious way to write a macro that does this, or is there a LaTeX package that does it already?

    Read the article

  • First Come, First Served process scheduling

    - by user253530
    i have 4 processes: p1 - bursts 5, priority: 3 p2 - bursts 8, priority: 2 p3 - bursts 12, priority: 2 p4 - bursts 6, priority: 1 Assuming that all processes arrive at the scheduler at the same time what is the average response time and average turnaround time? For FCFS is it ok to have them in the order p1, p2, p3, p4 in the execution queue?

    Read the article

  • 3d Model Scaling With Camera

    - by spasarto
    I have a very simple 3D maze program that uses a first person camera to navigate the maze. I'm trying to scale the blocks that make up the maze walls and floor so the corridors seem more roomy to the camera. Every time I scale the model, the camera seems to scale with it, and the corridors always stay the same width. I've tried apply the scale to the model in the content pipe (setting the scale property of the model in the properties window in VS). I've also tried to apply the scale using Matrix.CreateScale(float) using the Scale-Rotate-Transform order with the same result. If I leave the camera speed the same, the camera moves slower, so I know it's traversing a larger distance, but the world doesn't look larger; the camera just seems slower. I'm not sure what part of the code to include since I don't know if it is an issue with my model, camera, or something else. Any hints at what I'm doing wrong? Camera: Projection = Matrix.CreatePerspectiveFieldOfView( MathHelper.PiOver4, _device.Viewport.AspectRatio, 1.0f, 1000.0f ); Matrix camRotMatrix = Matrix.CreateRotationX( _cameraPitch ) * Matrix.CreateRotationY( _cameraYaw ); Vector3 transCamRef = Vector3.Transform( _cameraForward, camRotMatrix ); _cameraTarget = transCamRef + CameraPosition; Vector3 camRotUpVector = Vector3.Transform( _cameraUpVector, camRotMatrix ); View = Matrix.CreateLookAt( CameraPosition, _cameraTarget, camRotUpVector ); Model: World = Matrix.CreateTranslation( Position );

    Read the article

  • RC of Entity Framework 4.1 (which includes EF Code First)

    - by ScottGu
    Last week the data team shipped the Release Candidate of Entity Framework 4.1.  You can learn more about it and download it here. EF 4.1 includes the new “EF Code First” option that I’ve blogged about several times in the past.  EF Code First provides a really elegant and clean way to work with data, and enables you to do so without requiring a designer or XML mapping file.  Below are links to some tutorials I’ve written in the past about it: Code First Development with Entity Framework 4.x EF Code First: Custom Database Schema Mapping Using EF Code First with an Existing Database The above tutorials were written against the CTP4 release of EF Code First (and so some APIs might be a little different) – but the concepts and scenarios outlined in them are the same as with the RC. Go Live License Last week’s EF 4.1 RC ships with a “go live” license that enables you to use it in production environments.  The final release of EF 4.1 will ship within the next 4 weeks and will be 100% API compatible with the RC release. Improvements with the RC The RC includes several improvements and enhancements.  The EF team has a good blog post summarizing the RC changes.  Scott Hanselman also has a nice video interview with the data team that talks more about the release. One of my favorite improvements introduced with last week’s RC is its support for medium trust security.  This enables you to use EF 4.1 (and code-first) within low-cost ASP.NET shared hosting web environments – without requiring a hoster to install anything to use it. EF 4.1 also now supports validation with not only code-first scenarios, but also model-first and database-first workflows.  Upgrading from previous releases The RC does include a few API tweaks and changes from the prior CTP builds.  Read the release notes that come with the release to get a more detailed listing of the changes. John Papa also has an excellent Upgrading to EF 4.1 RC blog post that describes the steps he took when upgrading a large project he wrote with the previous CTP5 release.  The work to upgrade is pretty straight forward and easy – use his write-up as a guide on how to quickly update projects of your own. NuGet Package Rename One of the changes that the data team made between the CTP5 and RC releases was to rename the NuGet package name from “EFCodeFirst” to “EntityFramework”. They decided to make this change since the EF 4.1 release now includes several additions above and beyond just code first. If you already have installed the “EFCodeFirst” NuGet package, you’ll want to uninstall it and then install the new “EntityFramework” NuGet package.  John Papa’s blog post details the exact steps on how to do this (it only takes ~20 seconds to do this). More EF Tutorials Julie Lerman has created some nice whitepapers and tutorials for MSDN that show using the new EF4 and EF 4.1 feature set. Click here to find links to read and watch them. Summary I’m really excited about the EF 4.1 release that will be shipping next month.  It significantly improves the Entity Framework, and makes it even easier and cleaner to work with data inside of .NET.  You can take advantage of it within all ASP.NET projects (including both Web Forms and MVC), within client projects using Windows Forms and WPF, and within other project types like WCF, Console and Services.  You can use NuGet to easily install it within all of them. Hope this helps, Scott P.S. I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

    Read the article

  • Object reference case study

    - by Skogen
    When person 1 become partner with person 3, person 2 should no longer have person 1 as partner. How should I solve this? public class Person { private String name; private Person partner; public Person(String name){ this.name = name; } public void setPartner(Person partner){ this.partner = partner; partner.partner = this; } public static void main(String[] args) { Person one = new Person("1"); Person two = new Person("2"); Person three = new Person("3"); Person four = new Person("4"); one.setPartner(two); three.setPartner(four); one.setPartner(three); //Person two is still partner with person 1 }

    Read the article

  • Developing web apps using ASP.NET MVC 3, Razor and EF Code First - Part 1

    - by shiju
    In this post, I will demonstrate web application development using ASP. NET MVC 3, Razor and EF code First. This post will also cover Dependency Injection using Unity 2.0 and generic Repository and Unit of Work for EF Code First. The following frameworks will be used for this step by step tutorial. ASP.NET MVC 3 EF Code First CTP 5 Unity 2.0 Define Domain Model Let’s create domain model for our simple web application Category class public class Category {     public int CategoryId { get; set; }     [Required(ErrorMessage = "Name Required")]     [StringLength(25, ErrorMessage = "Must be less than 25 characters")]     public string Name { get; set;}     public string Description { get; set; }     public virtual ICollection<Expense> Expenses { get; set; } }   Expense class public class Expense {             public int ExpenseId { get; set; }            public string  Transaction { get; set; }     public DateTime Date { get; set; }     public double Amount { get; set; }     public int CategoryId { get; set; }     public virtual Category Category { get; set; } } We have two domain entities - Category and Expense. A single category contains a list of expense transactions and every expense transaction should have a Category. In this post, we will be focusing on CRUD operations for the entity Category and will be working on the Expense entity with a View Model object in the later post. And the source code for this application will be refactored over time. The above entities are very simple POCO (Plain Old CLR Object) classes and the entity Category is decorated with validation attributes in the System.ComponentModel.DataAnnotations namespace. Now we want to use these entities for defining model objects for the Entity Framework 4. Using the Code First approach of Entity Framework, we can first define the entities by simply writing POCO classes without any coupling with any API or database library. This approach lets you focus on domain model which will enable Domain-Driven Development for applications. EF code first support is currently enabled with a separate API that is runs on top of the Entity Framework 4. EF Code First is reached CTP 5 when I am writing this article. Creating Context Class for Entity Framework We have created our domain model and let’s create a class in order to working with Entity Framework Code First. For this, you have to download EF Code First CTP 5 and add reference to the assembly EntitFramework.dll. You can also use NuGet to download add reference to EEF Code First.    public class MyFinanceContext : DbContext {     public MyFinanceContext() : base("MyFinance") { }     public DbSet<Category> Categories { get; set; }     public DbSet<Expense> Expenses { get; set; }         }   The above class MyFinanceContext is derived from DbContext that can connect your model classes to a database. The MyFinanceContext class is mapping our Category and Expense class into database tables Categories and Expenses using DbSet<TEntity> where TEntity is any POCO class. When we are running the application at first time, it will automatically create the database. EF code-first look for a connection string in web.config or app.config that has the same name as the dbcontext class. If it is not find any connection string with the convention, it will automatically create database in local SQL Express database by default and the name of the database will be same name as the dbcontext class. You can also define the name of database in constructor of the the dbcontext class. Unlike NHibernate, we don’t have to use any XML based mapping files or Fluent interface for mapping between our model and database. The model classes of Code First are working on the basis of conventions and we can also use a fluent API to refine our model. The convention for primary key is ‘Id’ or ‘<class name>Id’.  If primary key properties are detected with type ‘int’, ‘long’ or ‘short’, they will automatically registered as identity columns in the database by default. Primary key detection is not case sensitive. We can define our model classes with validation attributes in the System.ComponentModel.DataAnnotations namespace and it automatically enforces validation rules when a model object is updated or saved. Generic Repository for EF Code First We have created model classes and dbcontext class. Now we have to create generic repository pattern for data persistence with EF code first. If you don’t know about the repository pattern, checkout Martin Fowler’s article on Repository Let’s create a generic repository to working with DbContext and DbSet generics. public interface IRepository<T> where T : class     {         void Add(T entity);         void Delete(T entity);         T GetById(long Id);         IEnumerable<T> All();     }   RepositoryBasse – Generic Repository class public abstract class RepositoryBase<T> where T : class { private MyFinanceContext database; private readonly IDbSet<T> dbset; protected RepositoryBase(IDatabaseFactory databaseFactory) {     DatabaseFactory = databaseFactory;     dbset = Database.Set<T>(); }   protected IDatabaseFactory DatabaseFactory {     get; private set; }   protected MyFinanceContext Database {     get { return database ?? (database = DatabaseFactory.Get()); } } public virtual void Add(T entity) {     dbset.Add(entity);            }        public virtual void Delete(T entity) {     dbset.Remove(entity); }   public virtual T GetById(long id) {     return dbset.Find(id); }   public virtual IEnumerable<T> All() {     return dbset.ToList(); } }   DatabaseFactory class public class DatabaseFactory : Disposable, IDatabaseFactory {     private MyFinanceContext database;     public MyFinanceContext Get()     {         return database ?? (database = new MyFinanceContext());     }     protected override void DisposeCore()     {         if (database != null)             database.Dispose();     } } Unit of Work If you are new to Unit of Work pattern, checkout Fowler’s article on Unit of Work . According to Martin Fowler, the Unit of Work pattern "maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems." Let’s create a class for handling Unit of Work   public interface IUnitOfWork {     void Commit(); }   UniOfWork class public class UnitOfWork : IUnitOfWork {     private readonly IDatabaseFactory databaseFactory;     private MyFinanceContext dataContext;       public UnitOfWork(IDatabaseFactory databaseFactory)     {         this.databaseFactory = databaseFactory;     }       protected MyFinanceContext DataContext     {         get { return dataContext ?? (dataContext = databaseFactory.Get()); }     }       public void Commit()     {         DataContext.Commit();     } }   The Commit method of the UnitOfWork will call the commit method of MyFinanceContext class and it will execute the SaveChanges method of DbContext class.   Repository class for Category In this post, we will be focusing on the persistence against Category entity and will working on other entities in later post. Let’s create a repository for handling CRUD operations for Category using derive from a generic Repository RepositoryBase<T>.   public class CategoryRepository: RepositoryBase<Category>, ICategoryRepository     {     public CategoryRepository(IDatabaseFactory databaseFactory)         : base(databaseFactory)         {         }                } public interface ICategoryRepository : IRepository<Category> { } If we need additional methods than generic repository for the Category, we can define in the CategoryRepository. Dependency Injection using Unity 2.0 If you are new to Inversion of Control/ Dependency Injection or Unity, please have a look on my articles at http://weblogs.asp.net/shijuvarghese/archive/tags/IoC/default.aspx. I want to create a custom lifetime manager for Unity to store container in the current HttpContext.   public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable {     public override object GetValue()     {         return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];     }     public override void RemoveValue()     {         HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName);     }     public override void SetValue(object newValue)     {         HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] = newValue;     }     public void Dispose()     {         RemoveValue();     } }   Let’s create controller factory for Unity in the ASP.NET MVC 3 application. public class UnityControllerFactory : DefaultControllerFactory { IUnityContainer container; public UnityControllerFactory(IUnityContainer container) {     this.container = container; } protected override IController GetControllerInstance(RequestContext reqContext, Type controllerType) {     IController controller;     if (controllerType == null)         throw new HttpException(                 404, String.Format(                     "The controller for path '{0}' could not be found" +     "or it does not implement IController.",                 reqContext.HttpContext.Request.Path));       if (!typeof(IController).IsAssignableFrom(controllerType))         throw new ArgumentException(                 string.Format(                     "Type requested is not a controller: {0}",                     controllerType.Name),                     "controllerType");     try     {         controller= container.Resolve(controllerType) as IController;     }     catch (Exception ex)     {         throw new InvalidOperationException(String.Format(                                 "Error resolving controller {0}",                                 controllerType.Name), ex);     }     return controller; }   }   Configure contract and concrete types in Unity Let’s configure our contract and concrete types in Unity for resolving our dependencies.   private void ConfigureUnity() {     //Create UnityContainer               IUnityContainer container = new UnityContainer()                 .RegisterType<IDatabaseFactory, DatabaseFactory>(new HttpContextLifetimeManager<IDatabaseFactory>())     .RegisterType<IUnitOfWork, UnitOfWork>(new HttpContextLifetimeManager<IUnitOfWork>())     .RegisterType<ICategoryRepository, CategoryRepository>(new HttpContextLifetimeManager<ICategoryRepository>());                 //Set container for Controller Factory                ControllerBuilder.Current.SetControllerFactory(             new UnityControllerFactory(container)); }   In the above ConfigureUnity method, we are registering our types onto Unity container with custom lifetime manager HttpContextLifetimeManager. Let’s call ConfigureUnity method in the Global.asax.cs for set controller factory for Unity and configuring the types with Unity.   protected void Application_Start() {     AreaRegistration.RegisterAllAreas();     RegisterGlobalFilters(GlobalFilters.Filters);     RegisterRoutes(RouteTable.Routes);     ConfigureUnity(); }   Developing web application using ASP.NET MVC 3 We have created our domain model for our web application and also have created repositories and configured dependencies with Unity container. Now we have to create controller classes and views for doing CRUD operations against the Category entity. Let’s create controller class for Category Category Controller   public class CategoryController : Controller {     private readonly ICategoryRepository categoryRepository;     private readonly IUnitOfWork unitOfWork;           public CategoryController(ICategoryRepository categoryRepository, IUnitOfWork unitOfWork)     {         this.categoryRepository = categoryRepository;         this.unitOfWork = unitOfWork;     }       public ActionResult Index()     {         var categories = categoryRepository.All();         return View(categories);     }     [HttpGet]     public ActionResult Edit(int id)     {         var category = categoryRepository.GetById(id);         return View(category);     }       [HttpPost]     public ActionResult Edit(int id, FormCollection collection)     {         var category = categoryRepository.GetById(id);         if (TryUpdateModel(category))         {             unitOfWork.Commit();             return RedirectToAction("Index");         }         else return View(category);                 }       [HttpGet]     public ActionResult Create()     {         var category = new Category();         return View(category);     }           [HttpPost]     public ActionResult Create(Category category)     {         if (!ModelState.IsValid)         {             return View("Create", category);         }                     categoryRepository.Add(category);         unitOfWork.Commit();         return RedirectToAction("Index");     }       [HttpPost]     public ActionResult Delete(int  id)     {         var category = categoryRepository.GetById(id);         categoryRepository.Delete(category);         unitOfWork.Commit();         var categories = categoryRepository.All();         return PartialView("CategoryList", categories);       }        }   Creating Views in Razor Now we are going to create views in Razor for our ASP.NET MVC 3 application.  Let’s create a partial view CategoryList.cshtml for listing category information and providing link for Edit and Delete operations. CategoryList.cshtml @using MyFinance.Helpers; @using MyFinance.Domain; @model IEnumerable<Category>      <table>         <tr>         <th>Actions</th>         <th>Name</th>          <th>Description</th>         </tr>     @foreach (var item in Model) {             <tr>             <td>                 @Html.ActionLink("Edit", "Edit",new { id = item.CategoryId })                 @Ajax.ActionLink("Delete", "Delete", new { id = item.CategoryId }, new AjaxOptions { Confirm = "Delete Expense?", HttpMethod = "Post", UpdateTargetId = "divCategoryList" })                           </td>             <td>                 @item.Name             </td>             <td>                 @item.Description             </td>         </tr>          }       </table>     <p>         @Html.ActionLink("Create New", "Create")     </p> The delete link is providing Ajax functionality using the Ajax.ActionLink. This will call an Ajax request for Delete action method in the CategoryCotroller class. In the Delete action method, it will return Partial View CategoryList after deleting the record. We are using CategoryList view for the Ajax functionality and also for Index view using for displaying list of category information. Let’s create Index view using partial view CategoryList  Index.chtml @model IEnumerable<MyFinance.Domain.Category> @{     ViewBag.Title = "Index"; }    <h2>Category List</h2>    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>    <div id="divCategoryList">               @Html.Partial("CategoryList", Model) </div>   We can call the partial views using Html.Partial helper method. Now we are going to create View pages for insert and update functionality for the Category. Both view pages are sharing common user interface for entering the category information. So I want to create an EditorTemplate for the Category information. We have to create the EditorTemplate with the same name of entity object so that we can refer it on view pages using @Html.EditorFor(model => model) . So let’s create template with name Category. Let’s create view page for insert Category information   @model MyFinance.Domain.Category   @{     ViewBag.Title = "Save"; }   <h2>Create</h2>   <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>   @using (Html.BeginForm()) {     @Html.ValidationSummary(true)     <fieldset>         <legend>Category</legend>                @Html.EditorFor(model => model)               <p>             <input type="submit" value="Create" />         </p>     </fieldset> }   <div>     @Html.ActionLink("Back to List", "Index") </div> ViewStart file In Razor views, we can add a file named _viewstart.cshtml in the views directory  and this will be shared among the all views with in the Views directory. The below code in the _viewstart.cshtml, sets the Layout page for every Views in the Views folder.      @{     Layout = "~/Views/Shared/_Layout.cshtml"; }   Source Code You can download the source code from http://efmvc.codeplex.com/ . The source will be refactored on over time.   Summary In this post, we have created a simple web application using ASP.NET MVC 3 and EF Code First. We have discussed on technologies and practices such as ASP.NET MVC 3, Razor, EF Code First, Unity 2, generic Repository and Unit of Work. In my later posts, I will modify the application and will be discussed on more things. Stay tuned to my blog  for more posts on step by step application building.

    Read the article

  • Announcing Entity Framework Code-First (CTP 5 release)

    In this article, Scott provides a detailed coverage of Entity Framework Code-First CTP 5 release and the features included with the build. He begins with the steps required to install EF Code First. Scott then examines the usage of EF Code First to create a model layer for the Northwind sample database in a series of steps. Towards the end of the article, Scott examines the usage of UI Validation and few addtional EF Code First Improvements shipped with CTP 5.

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >